file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./full_match/43113/0x91c945920adFfF698b865b6B71CCefE005B5E3d3/sources/Vikings.sol
|
MINTING & CLAIMING FUNCTIONALITY Calculate the total mint fee of the transaction. Cache the running mint fee.
|
function mintViking(uint256 minting) public virtual payable {
require(saleStarted, "SALE NOT STARTED");
require(getTotalMinted() < MAX_MINT, "SALE HAS ENDED");
require(minting > 0 && minting <= 10, "INVALID MINT AMOUNT");
require(getTotalMinted().add(minting) <= MAX_MINT, "MINT WOULD EXCEED TOKEN LIMIT");
uint256[] memory mintFees = new uint256[](10);
uint256 mintIndex = getTotalMinted();
uint256 totalFee = 0;
for (uint i = 0; i < minting; i++) {
mintFees[i] = getMintFee(mintIndex + i);
totalFee += mintFees[i];
}
require(msg.value >= totalFee, "NOT ENOUGH AVAX PAID");
mintIndex += 1;
for (uint i = 0; i < minting; i++) {
_safeMint(msg.sender, mintIndex + i);
minter[mintIndex + i] = msg.sender;
uint256 rewardSplit = distributeFees(mintFees[i]);
RewardsClaimedAt[mintIndex + i] = RunningMintFee;
RunningMintFee += rewardSplit / totalSupply();
emit Minted(mintIndex + i, msg.sender, mintFees[i]);
}
| 7,170,286 |
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol";
import { IController } from "../../interfaces/IController.sol";
import { ISetValuer } from "../../interfaces/ISetValuer.sol";
import { INAVIssuanceHook } from "../../interfaces/INAVIssuanceHook.sol";
import { Invoke } from "../lib/Invoke.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { IWETH } from "../../interfaces/external/IWETH.sol";
import { ModuleBase } from "../lib/ModuleBase.sol";
import { Position } from "../lib/Position.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
import { ResourceIdentifier } from "../lib/ResourceIdentifier.sol";
/**
* @title CustomOracleNavIssuanceModule
* @author Set Protocol
*
* Module that enables issuance and redemption with any valid ERC20 token or ETH if allowed by the manager. Sender receives
* a proportional amount of SetTokens on issuance or ERC20 token on redemption based on the calculated net asset value using
* oracle prices. Manager is able to enforce a premium / discount on issuance / redemption to avoid arbitrage and front
* running when relying on oracle prices. Managers can charge a fee (denominated in reserve asset).
*/
contract CustomOracleNavIssuanceModule is ModuleBase, ReentrancyGuard {
using AddressArrayUtils for address[];
using Invoke for ISetToken;
using Position for ISetToken;
using PreciseUnitMath for uint256;
using PreciseUnitMath for int256;
using ResourceIdentifier for IController;
using SafeMath for uint256;
using SafeCast for int256;
using SafeCast for uint256;
using SignedSafeMath for int256;
/* ============ Events ============ */
event SetTokenNAVIssued(
ISetToken indexed _setToken,
address _issuer,
address _to,
address _reserveAsset,
address _hookContract,
uint256 _setTokenQuantity,
uint256 _managerFee,
uint256 _premium
);
event SetTokenNAVRedeemed(
ISetToken indexed _setToken,
address _redeemer,
address _to,
address _reserveAsset,
address _hookContract,
uint256 _setTokenQuantity,
uint256 _managerFee,
uint256 _premium
);
event ReserveAssetAdded(
ISetToken indexed _setToken,
address _newReserveAsset
);
event ReserveAssetRemoved(
ISetToken indexed _setToken,
address _removedReserveAsset
);
event PremiumEdited(
ISetToken indexed _setToken,
uint256 _newPremium
);
event ManagerFeeEdited(
ISetToken indexed _setToken,
uint256 _newManagerFee,
uint256 _index
);
event FeeRecipientEdited(
ISetToken indexed _setToken,
address _feeRecipient
);
/* ============ Structs ============ */
struct NAVIssuanceSettings {
INAVIssuanceHook managerIssuanceHook; // Issuance hook configurations
INAVIssuanceHook managerRedemptionHook; // Redemption hook configurations
ISetValuer setValuer; // Optional custom set valuer. If address(0) is provided, fetch the default one from the controller
address[] reserveAssets; // Allowed reserve assets - Must have a price enabled with the price oracle
address feeRecipient; // Manager fee recipient
uint256[2] managerFees; // Manager fees. 0 index is issue and 1 index is redeem fee (0.01% = 1e14, 1% = 1e16)
uint256 maxManagerFee; // Maximum fee manager is allowed to set for issue and redeem
uint256 premiumPercentage; // Premium percentage (0.01% = 1e14, 1% = 1e16). This premium is a buffer around oracle
// prices paid by user to the SetToken, which prevents arbitrage and oracle front running
uint256 maxPremiumPercentage; // Maximum premium percentage manager is allowed to set (configured by manager)
uint256 minSetTokenSupply; // Minimum SetToken supply required for issuance and redemption
// to prevent dramatic inflationary changes to the SetToken's position multiplier
}
struct ActionInfo {
uint256 preFeeReserveQuantity; // Reserve value before fees; During issuance, represents raw quantity
// During redeem, represents post-premium value
uint256 protocolFees; // Total protocol fees (direct + manager revenue share)
uint256 managerFee; // Total manager fee paid in reserve asset
uint256 netFlowQuantity; // When issuing, quantity of reserve asset sent to SetToken
// When redeeming, quantity of reserve asset sent to redeemer
uint256 setTokenQuantity; // When issuing, quantity of SetTokens minted to mintee
// When redeeming, quantity of SetToken redeemed
uint256 previousSetTokenSupply; // SetToken supply prior to issue/redeem action
uint256 newSetTokenSupply; // SetToken supply after issue/redeem action
int256 newPositionMultiplier; // SetToken position multiplier after issue/redeem
uint256 newReservePositionUnit; // SetToken reserve asset position unit after issue/redeem
}
/* ============ State Variables ============ */
// Wrapped ETH address
IWETH public immutable weth;
// Mapping of SetToken to NAV issuance settings struct
mapping(ISetToken => NAVIssuanceSettings) public navIssuanceSettings;
// Mapping to efficiently check a SetToken's reserve asset validity
// SetToken => reserveAsset => isReserveAsset
mapping(ISetToken => mapping(address => bool)) public isReserveAsset;
/* ============ Constants ============ */
// 0 index stores the manager fee in managerFees array, percentage charged on issue (denominated in reserve asset)
uint256 constant internal MANAGER_ISSUE_FEE_INDEX = 0;
// 1 index stores the manager fee percentage in managerFees array, charged on redeem
uint256 constant internal MANAGER_REDEEM_FEE_INDEX = 1;
// 0 index stores the manager revenue share protocol fee % on the controller, charged in the issuance function
uint256 constant internal PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX = 0;
// 1 index stores the manager revenue share protocol fee % on the controller, charged in the redeem function
uint256 constant internal PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX = 1;
// 2 index stores the direct protocol fee % on the controller, charged in the issuance function
uint256 constant internal PROTOCOL_ISSUE_DIRECT_FEE_INDEX = 2;
// 3 index stores the direct protocol fee % on the controller, charged in the redeem function
uint256 constant internal PROTOCOL_REDEEM_DIRECT_FEE_INDEX = 3;
/* ============ Constructor ============ */
/**
* @param _controller Address of controller contract
* @param _weth Address of wrapped eth
*/
constructor(IController _controller, IWETH _weth) public ModuleBase(_controller) {
weth = _weth;
}
/* ============ External Functions ============ */
/**
* Deposits the allowed reserve asset into the SetToken and mints the appropriate % of Net Asset Value of the SetToken
* to the specified _to address.
*
* @param _setToken Instance of the SetToken contract
* @param _reserveAsset Address of the reserve asset to issue with
* @param _reserveAssetQuantity Quantity of the reserve asset to issue with
* @param _minSetTokenReceiveQuantity Min quantity of SetToken to receive after issuance
* @param _to Address to mint SetToken to
*/
function issue(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity,
uint256 _minSetTokenReceiveQuantity,
address _to
)
external
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
_validateCommon(_setToken, _reserveAsset, _reserveAssetQuantity);
_callPreIssueHooks(_setToken, _reserveAsset, _reserveAssetQuantity, msg.sender, _to);
ActionInfo memory issueInfo = _createIssuanceInfo(_setToken, _reserveAsset, _reserveAssetQuantity);
_validateIssuanceInfo(_setToken, _minSetTokenReceiveQuantity, issueInfo);
_transferCollateralAndHandleFees(_setToken, IERC20(_reserveAsset), issueInfo);
_handleIssueStateUpdates(_setToken, _reserveAsset, _to, issueInfo);
}
/**
* Wraps ETH and deposits WETH if allowed into the SetToken and mints the appropriate % of Net Asset Value of the SetToken
* to the specified _to address.
*
* @param _setToken Instance of the SetToken contract
* @param _minSetTokenReceiveQuantity Min quantity of SetToken to receive after issuance
* @param _to Address to mint SetToken to
*/
function issueWithEther(
ISetToken _setToken,
uint256 _minSetTokenReceiveQuantity,
address _to
)
external
payable
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
weth.deposit{ value: msg.value }();
_validateCommon(_setToken, address(weth), msg.value);
_callPreIssueHooks(_setToken, address(weth), msg.value, msg.sender, _to);
ActionInfo memory issueInfo = _createIssuanceInfo(_setToken, address(weth), msg.value);
_validateIssuanceInfo(_setToken, _minSetTokenReceiveQuantity, issueInfo);
_transferWETHAndHandleFees(_setToken, issueInfo);
_handleIssueStateUpdates(_setToken, address(weth), _to, issueInfo);
}
/**
* Redeems a SetToken into a valid reserve asset representing the appropriate % of Net Asset Value of the SetToken
* to the specified _to address. Only valid if there are available reserve units on the SetToken.
*
* @param _setToken Instance of the SetToken contract
* @param _reserveAsset Address of the reserve asset to redeem with
* @param _setTokenQuantity Quantity of SetTokens to redeem
* @param _minReserveReceiveQuantity Min quantity of reserve asset to receive
* @param _to Address to redeem reserve asset to
*/
function redeem(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity,
uint256 _minReserveReceiveQuantity,
address _to
)
external
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
_validateCommon(_setToken, _reserveAsset, _setTokenQuantity);
_callPreRedeemHooks(_setToken, _setTokenQuantity, msg.sender, _to);
ActionInfo memory redeemInfo = _createRedemptionInfo(_setToken, _reserveAsset, _setTokenQuantity);
_validateRedemptionInfo(_setToken, _minReserveReceiveQuantity, _setTokenQuantity, redeemInfo);
_setToken.burn(msg.sender, _setTokenQuantity);
// Instruct the SetToken to transfer the reserve asset back to the user
_setToken.strictInvokeTransfer(
_reserveAsset,
_to,
redeemInfo.netFlowQuantity
);
_handleRedemptionFees(_setToken, _reserveAsset, redeemInfo);
_handleRedeemStateUpdates(_setToken, _reserveAsset, _to, redeemInfo);
}
/**
* Redeems a SetToken into Ether (if WETH is valid) representing the appropriate % of Net Asset Value of the SetToken
* to the specified _to address. Only valid if there are available WETH units on the SetToken.
*
* @param _setToken Instance of the SetToken contract
* @param _setTokenQuantity Quantity of SetTokens to redeem
* @param _minReserveReceiveQuantity Min quantity of reserve asset to receive
* @param _to Address to redeem reserve asset to
*/
function redeemIntoEther(
ISetToken _setToken,
uint256 _setTokenQuantity,
uint256 _minReserveReceiveQuantity,
address payable _to
)
external
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
_validateCommon(_setToken, address(weth), _setTokenQuantity);
_callPreRedeemHooks(_setToken, _setTokenQuantity, msg.sender, _to);
ActionInfo memory redeemInfo = _createRedemptionInfo(_setToken, address(weth), _setTokenQuantity);
_validateRedemptionInfo(_setToken, _minReserveReceiveQuantity, _setTokenQuantity, redeemInfo);
_setToken.burn(msg.sender, _setTokenQuantity);
// Instruct the SetToken to transfer WETH from SetToken to module
_setToken.strictInvokeTransfer(
address(weth),
address(this),
redeemInfo.netFlowQuantity
);
weth.withdraw(redeemInfo.netFlowQuantity);
_to.transfer(redeemInfo.netFlowQuantity);
_handleRedemptionFees(_setToken, address(weth), redeemInfo);
_handleRedeemStateUpdates(_setToken, address(weth), _to, redeemInfo);
}
/**
* SET MANAGER ONLY. Add an allowed reserve asset
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset to add
*/
function addReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) {
require(!isReserveAsset[_setToken][_reserveAsset], "Reserve asset already exists");
navIssuanceSettings[_setToken].reserveAssets.push(_reserveAsset);
isReserveAsset[_setToken][_reserveAsset] = true;
emit ReserveAssetAdded(_setToken, _reserveAsset);
}
/**
* SET MANAGER ONLY. Remove a reserve asset
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset to remove
*/
function removeReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) {
require(isReserveAsset[_setToken][_reserveAsset], "Reserve asset does not exist");
navIssuanceSettings[_setToken].reserveAssets = navIssuanceSettings[_setToken].reserveAssets.remove(_reserveAsset);
delete isReserveAsset[_setToken][_reserveAsset];
emit ReserveAssetRemoved(_setToken, _reserveAsset);
}
/**
* SET MANAGER ONLY. Edit the premium percentage
*
* @param _setToken Instance of the SetToken
* @param _premiumPercentage Premium percentage in 10e16 (e.g. 10e16 = 1%)
*/
function editPremium(ISetToken _setToken, uint256 _premiumPercentage) external onlyManagerAndValidSet(_setToken) {
require(_premiumPercentage <= navIssuanceSettings[_setToken].maxPremiumPercentage, "Premium must be less than maximum allowed");
navIssuanceSettings[_setToken].premiumPercentage = _premiumPercentage;
emit PremiumEdited(_setToken, _premiumPercentage);
}
/**
* SET MANAGER ONLY. Edit manager fee
*
* @param _setToken Instance of the SetToken
* @param _managerFeePercentage Manager fee percentage in 10e16 (e.g. 10e16 = 1%)
* @param _managerFeeIndex Manager fee index. 0 index is issue fee, 1 index is redeem fee
*/
function editManagerFee(
ISetToken _setToken,
uint256 _managerFeePercentage,
uint256 _managerFeeIndex
)
external
onlyManagerAndValidSet(_setToken)
{
require(_managerFeePercentage <= navIssuanceSettings[_setToken].maxManagerFee, "Manager fee must be less than maximum allowed");
navIssuanceSettings[_setToken].managerFees[_managerFeeIndex] = _managerFeePercentage;
emit ManagerFeeEdited(_setToken, _managerFeePercentage, _managerFeeIndex);
}
/**
* SET MANAGER ONLY. Edit the manager fee recipient
*
* @param _setToken Instance of the SetToken
* @param _managerFeeRecipient Manager fee recipient
*/
function editFeeRecipient(ISetToken _setToken, address _managerFeeRecipient) external onlyManagerAndValidSet(_setToken) {
require(_managerFeeRecipient != address(0), "Fee recipient must not be 0 address");
navIssuanceSettings[_setToken].feeRecipient = _managerFeeRecipient;
emit FeeRecipientEdited(_setToken, _managerFeeRecipient);
}
/**
* SET MANAGER ONLY. Initializes this module to the SetToken with hooks, allowed reserve assets,
* fees and issuance premium. Only callable by the SetToken's manager. Hook addresses are optional.
* Address(0) means that no hook will be called.
*
* @param _setToken Instance of the SetToken to issue
* @param _navIssuanceSettings NAVIssuanceSettings struct defining parameters
*/
function initialize(
ISetToken _setToken,
NAVIssuanceSettings memory _navIssuanceSettings
)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
require(_navIssuanceSettings.reserveAssets.length > 0, "Reserve assets must be greater than 0");
require(_navIssuanceSettings.maxManagerFee < PreciseUnitMath.preciseUnit(), "Max manager fee must be less than 100%");
require(_navIssuanceSettings.maxPremiumPercentage < PreciseUnitMath.preciseUnit(), "Max premium percentage must be less than 100%");
require(_navIssuanceSettings.managerFees[0] <= _navIssuanceSettings.maxManagerFee, "Manager issue fee must be less than max");
require(_navIssuanceSettings.managerFees[1] <= _navIssuanceSettings.maxManagerFee, "Manager redeem fee must be less than max");
require(_navIssuanceSettings.premiumPercentage <= _navIssuanceSettings.maxPremiumPercentage, "Premium must be less than max");
require(_navIssuanceSettings.feeRecipient != address(0), "Fee Recipient must be non-zero address.");
// Initial mint of Set cannot use NAVIssuance since minSetTokenSupply must be > 0
require(_navIssuanceSettings.minSetTokenSupply > 0, "Min SetToken supply must be greater than 0");
for (uint256 i = 0; i < _navIssuanceSettings.reserveAssets.length; i++) {
require(!isReserveAsset[_setToken][_navIssuanceSettings.reserveAssets[i]], "Reserve assets must be unique");
isReserveAsset[_setToken][_navIssuanceSettings.reserveAssets[i]] = true;
}
navIssuanceSettings[_setToken] = _navIssuanceSettings;
_setToken.initializeModule();
}
/**
* Removes this module from the SetToken, via call by the SetToken. Issuance settings and
* reserve asset states are deleted.
*/
function removeModule() external override {
ISetToken setToken = ISetToken(msg.sender);
for (uint256 i = 0; i < navIssuanceSettings[setToken].reserveAssets.length; i++) {
delete isReserveAsset[setToken][navIssuanceSettings[setToken].reserveAssets[i]];
}
delete navIssuanceSettings[setToken];
}
receive() external payable {}
/* ============ External Getter Functions ============ */
function getReserveAssets(ISetToken _setToken) external view returns (address[] memory) {
return navIssuanceSettings[_setToken].reserveAssets;
}
function getIssuePremium(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
external
view
returns (uint256)
{
return _getIssuePremium(_setToken, _reserveAsset, _reserveAssetQuantity);
}
function getRedeemPremium(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
external
view
returns (uint256)
{
return _getRedeemPremium(_setToken, _reserveAsset, _setTokenQuantity);
}
function getManagerFee(ISetToken _setToken, uint256 _managerFeeIndex) external view returns (uint256) {
return navIssuanceSettings[_setToken].managerFees[_managerFeeIndex];
}
/**
* Get the expected SetTokens minted to recipient on issuance
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset
* @param _reserveAssetQuantity Quantity of the reserve asset to issue with
*
* @return uint256 Expected SetTokens to be minted to recipient
*/
function getExpectedSetTokenIssueQuantity(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
external
view
returns (uint256)
{
(,, uint256 netReserveFlow) = _getFees(
_setToken,
_reserveAssetQuantity,
PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_ISSUE_DIRECT_FEE_INDEX,
MANAGER_ISSUE_FEE_INDEX
);
uint256 setTotalSupply = _setToken.totalSupply();
return _getSetTokenMintQuantity(
_setToken,
_reserveAsset,
netReserveFlow,
setTotalSupply
);
}
/**
* Get the expected reserve asset to be redeemed
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset
* @param _setTokenQuantity Quantity of SetTokens to redeem
*
* @return uint256 Expected reserve asset quantity redeemed
*/
function getExpectedReserveRedeemQuantity(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
external
view
returns (uint256)
{
uint256 preFeeReserveQuantity = _getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity);
(,, uint256 netReserveFlows) = _getFees(
_setToken,
preFeeReserveQuantity,
PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_REDEEM_DIRECT_FEE_INDEX,
MANAGER_REDEEM_FEE_INDEX
);
return netReserveFlows;
}
/**
* Checks if issue is valid
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset
* @param _reserveAssetQuantity Quantity of the reserve asset to issue with
*
* @return bool Returns true if issue is valid
*/
function isIssueValid(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
external
view
returns (bool)
{
uint256 setTotalSupply = _setToken.totalSupply();
return _reserveAssetQuantity != 0
&& isReserveAsset[_setToken][_reserveAsset]
&& setTotalSupply >= navIssuanceSettings[_setToken].minSetTokenSupply;
}
/**
* Checks if redeem is valid
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset
* @param _setTokenQuantity Quantity of SetTokens to redeem
*
* @return bool Returns true if redeem is valid
*/
function isRedeemValid(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
external
view
returns (bool)
{
uint256 setTotalSupply = _setToken.totalSupply();
if (
_setTokenQuantity == 0
|| !isReserveAsset[_setToken][_reserveAsset]
|| setTotalSupply < navIssuanceSettings[_setToken].minSetTokenSupply.add(_setTokenQuantity)
) {
return false;
} else {
uint256 totalRedeemValue =_getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity);
(,, uint256 expectedRedeemQuantity) = _getFees(
_setToken,
totalRedeemValue,
PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_REDEEM_DIRECT_FEE_INDEX,
MANAGER_REDEEM_FEE_INDEX
);
uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256();
return existingUnit.preciseMul(setTotalSupply) >= expectedRedeemQuantity;
}
}
/* ============ Internal Functions ============ */
function _validateCommon(ISetToken _setToken, address _reserveAsset, uint256 _quantity) internal view {
require(_quantity > 0, "Quantity must be > 0");
require(isReserveAsset[_setToken][_reserveAsset], "Must be valid reserve asset");
}
function _validateIssuanceInfo(ISetToken _setToken, uint256 _minSetTokenReceiveQuantity, ActionInfo memory _issueInfo) internal view {
// Check that total supply is greater than min supply needed for issuance
// Note: A min supply amount is needed to avoid division by 0 when SetToken supply is 0
require(
_issueInfo.previousSetTokenSupply >= navIssuanceSettings[_setToken].minSetTokenSupply,
"Supply must be greater than minimum to enable issuance"
);
require(_issueInfo.setTokenQuantity >= _minSetTokenReceiveQuantity, "Must be greater than min SetToken");
}
function _validateRedemptionInfo(
ISetToken _setToken,
uint256 _minReserveReceiveQuantity,
uint256 _setTokenQuantity,
ActionInfo memory _redeemInfo
)
internal
view
{
// Check that new supply is more than min supply needed for redemption
// Note: A min supply amount is needed to avoid division by 0 when redeeming SetToken to 0
require(
_redeemInfo.newSetTokenSupply >= navIssuanceSettings[_setToken].minSetTokenSupply,
"Supply must be greater than minimum to enable redemption"
);
require(_redeemInfo.netFlowQuantity >= _minReserveReceiveQuantity, "Must be greater than min receive reserve quantity");
}
function _createIssuanceInfo(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
internal
view
returns (ActionInfo memory)
{
ActionInfo memory issueInfo;
issueInfo.previousSetTokenSupply = _setToken.totalSupply();
issueInfo.preFeeReserveQuantity = _reserveAssetQuantity;
(issueInfo.protocolFees, issueInfo.managerFee, issueInfo.netFlowQuantity) = _getFees(
_setToken,
issueInfo.preFeeReserveQuantity,
PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_ISSUE_DIRECT_FEE_INDEX,
MANAGER_ISSUE_FEE_INDEX
);
issueInfo.setTokenQuantity = _getSetTokenMintQuantity(
_setToken,
_reserveAsset,
issueInfo.netFlowQuantity,
issueInfo.previousSetTokenSupply
);
(issueInfo.newSetTokenSupply, issueInfo.newPositionMultiplier) = _getIssuePositionMultiplier(_setToken, issueInfo);
issueInfo.newReservePositionUnit = _getIssuePositionUnit(_setToken, _reserveAsset, issueInfo);
return issueInfo;
}
function _createRedemptionInfo(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
internal
view
returns (ActionInfo memory)
{
ActionInfo memory redeemInfo;
redeemInfo.setTokenQuantity = _setTokenQuantity;
redeemInfo.preFeeReserveQuantity =_getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity);
(redeemInfo.protocolFees, redeemInfo.managerFee, redeemInfo.netFlowQuantity) = _getFees(
_setToken,
redeemInfo.preFeeReserveQuantity,
PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_REDEEM_DIRECT_FEE_INDEX,
MANAGER_REDEEM_FEE_INDEX
);
redeemInfo.previousSetTokenSupply = _setToken.totalSupply();
(redeemInfo.newSetTokenSupply, redeemInfo.newPositionMultiplier) = _getRedeemPositionMultiplier(_setToken, _setTokenQuantity, redeemInfo);
redeemInfo.newReservePositionUnit = _getRedeemPositionUnit(_setToken, _reserveAsset, redeemInfo);
return redeemInfo;
}
/**
* Transfer reserve asset from user to SetToken and fees from user to appropriate fee recipients
*/
function _transferCollateralAndHandleFees(ISetToken _setToken, IERC20 _reserveAsset, ActionInfo memory _issueInfo) internal {
transferFrom(_reserveAsset, msg.sender, address(_setToken), _issueInfo.netFlowQuantity);
if (_issueInfo.protocolFees > 0) {
transferFrom(_reserveAsset, msg.sender, controller.feeRecipient(), _issueInfo.protocolFees);
}
if (_issueInfo.managerFee > 0) {
transferFrom(_reserveAsset, msg.sender, navIssuanceSettings[_setToken].feeRecipient, _issueInfo.managerFee);
}
}
/**
* Transfer WETH from module to SetToken and fees from module to appropriate fee recipients
*/
function _transferWETHAndHandleFees(ISetToken _setToken, ActionInfo memory _issueInfo) internal {
weth.transfer(address(_setToken), _issueInfo.netFlowQuantity);
if (_issueInfo.protocolFees > 0) {
weth.transfer(controller.feeRecipient(), _issueInfo.protocolFees);
}
if (_issueInfo.managerFee > 0) {
weth.transfer(navIssuanceSettings[_setToken].feeRecipient, _issueInfo.managerFee);
}
}
function _handleIssueStateUpdates(
ISetToken _setToken,
address _reserveAsset,
address _to,
ActionInfo memory _issueInfo
)
internal
{
_setToken.editPositionMultiplier(_issueInfo.newPositionMultiplier);
_setToken.editDefaultPosition(_reserveAsset, _issueInfo.newReservePositionUnit);
_setToken.mint(_to, _issueInfo.setTokenQuantity);
emit SetTokenNAVIssued(
_setToken,
msg.sender,
_to,
_reserveAsset,
address(navIssuanceSettings[_setToken].managerIssuanceHook),
_issueInfo.setTokenQuantity,
_issueInfo.managerFee,
_issueInfo.protocolFees
);
}
function _handleRedeemStateUpdates(
ISetToken _setToken,
address _reserveAsset,
address _to,
ActionInfo memory _redeemInfo
)
internal
{
_setToken.editPositionMultiplier(_redeemInfo.newPositionMultiplier);
_setToken.editDefaultPosition(_reserveAsset, _redeemInfo.newReservePositionUnit);
emit SetTokenNAVRedeemed(
_setToken,
msg.sender,
_to,
_reserveAsset,
address(navIssuanceSettings[_setToken].managerRedemptionHook),
_redeemInfo.setTokenQuantity,
_redeemInfo.managerFee,
_redeemInfo.protocolFees
);
}
function _handleRedemptionFees(ISetToken _setToken, address _reserveAsset, ActionInfo memory _redeemInfo) internal {
// Instruct the SetToken to transfer protocol fee to fee recipient if there is a fee
payProtocolFeeFromSetToken(_setToken, _reserveAsset, _redeemInfo.protocolFees);
// Instruct the SetToken to transfer manager fee to manager fee recipient if there is a fee
if (_redeemInfo.managerFee > 0) {
_setToken.strictInvokeTransfer(
_reserveAsset,
navIssuanceSettings[_setToken].feeRecipient,
_redeemInfo.managerFee
);
}
}
/**
* Returns the issue premium percentage. Virtual function that can be overridden in future versions of the module
* and can contain arbitrary logic to calculate the issuance premium.
*/
function _getIssuePremium(
ISetToken _setToken,
address /* _reserveAsset */,
uint256 /* _reserveAssetQuantity */
)
virtual
internal
view
returns (uint256)
{
return navIssuanceSettings[_setToken].premiumPercentage;
}
/**
* Returns the redeem premium percentage. Virtual function that can be overridden in future versions of the module
* and can contain arbitrary logic to calculate the redemption premium.
*/
function _getRedeemPremium(
ISetToken _setToken,
address /* _reserveAsset */,
uint256 /* _setTokenQuantity */
)
virtual
internal
view
returns (uint256)
{
return navIssuanceSettings[_setToken].premiumPercentage;
}
/**
* Returns the fees attributed to the manager and the protocol. The fees are calculated as follows:
*
* ManagerFee = (manager fee % - % to protocol) * reserveAssetQuantity
* Protocol Fee = (% manager fee share + direct fee %) * reserveAssetQuantity
*
* @param _setToken Instance of the SetToken
* @param _reserveAssetQuantity Quantity of reserve asset to calculate fees from
* @param _protocolManagerFeeIndex Index to pull rev share NAV Issuance fee from the Controller
* @param _protocolDirectFeeIndex Index to pull direct NAV issuance fee from the Controller
* @param _managerFeeIndex Index from NAVIssuanceSettings (0 = issue fee, 1 = redeem fee)
*
* @return uint256 Fees paid to the protocol in reserve asset
* @return uint256 Fees paid to the manager in reserve asset
* @return uint256 Net reserve to user net of fees
*/
function _getFees(
ISetToken _setToken,
uint256 _reserveAssetQuantity,
uint256 _protocolManagerFeeIndex,
uint256 _protocolDirectFeeIndex,
uint256 _managerFeeIndex
)
internal
view
returns (uint256, uint256, uint256)
{
(uint256 protocolFeePercentage, uint256 managerFeePercentage) = _getProtocolAndManagerFeePercentages(
_setToken,
_protocolManagerFeeIndex,
_protocolDirectFeeIndex,
_managerFeeIndex
);
// Calculate total notional fees
uint256 protocolFees = protocolFeePercentage.preciseMul(_reserveAssetQuantity);
uint256 managerFee = managerFeePercentage.preciseMul(_reserveAssetQuantity);
uint256 netReserveFlow = _reserveAssetQuantity.sub(protocolFees).sub(managerFee);
return (protocolFees, managerFee, netReserveFlow);
}
function _getProtocolAndManagerFeePercentages(
ISetToken _setToken,
uint256 _protocolManagerFeeIndex,
uint256 _protocolDirectFeeIndex,
uint256 _managerFeeIndex
)
internal
view
returns(uint256, uint256)
{
// Get protocol fee percentages
uint256 protocolDirectFeePercent = controller.getModuleFee(address(this), _protocolDirectFeeIndex);
uint256 protocolManagerShareFeePercent = controller.getModuleFee(address(this), _protocolManagerFeeIndex);
uint256 managerFeePercent = navIssuanceSettings[_setToken].managerFees[_managerFeeIndex];
// Calculate revenue share split percentage
uint256 protocolRevenueSharePercentage = protocolManagerShareFeePercent.preciseMul(managerFeePercent);
uint256 managerRevenueSharePercentage = managerFeePercent.sub(protocolRevenueSharePercentage);
uint256 totalProtocolFeePercentage = protocolRevenueSharePercentage.add(protocolDirectFeePercent);
return (totalProtocolFeePercentage, managerRevenueSharePercentage);
}
function _getSetTokenMintQuantity(
ISetToken _setToken,
address _reserveAsset,
uint256 _netReserveFlows, // Value of reserve asset net of fees
uint256 _setTotalSupply
)
internal
view
returns (uint256)
{
uint256 premiumPercentage = _getIssuePremium(_setToken, _reserveAsset, _netReserveFlows);
uint256 premiumValue = _netReserveFlows.preciseMul(premiumPercentage);
// If the set manager provided a custom valuer at initialization time, use it. Otherwise get it from the controller
// Get valuation of the SetToken with the quote asset as the reserve asset. Returns value in precise units (1e18)
// Reverts if price is not found
uint256 setTokenValuation = _getSetValuer(_setToken).calculateSetTokenValuation(_setToken, _reserveAsset);
// Get reserve asset decimals
uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals();
uint256 normalizedTotalReserveQuantityNetFees = _netReserveFlows.preciseDiv(10 ** reserveAssetDecimals);
uint256 normalizedTotalReserveQuantityNetFeesAndPremium = _netReserveFlows.sub(premiumValue).preciseDiv(10 ** reserveAssetDecimals);
// Calculate SetTokens to mint to issuer
uint256 denominator = _setTotalSupply.preciseMul(setTokenValuation).add(normalizedTotalReserveQuantityNetFees).sub(normalizedTotalReserveQuantityNetFeesAndPremium);
return normalizedTotalReserveQuantityNetFeesAndPremium.preciseMul(_setTotalSupply).preciseDiv(denominator);
}
function _getRedeemReserveQuantity(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
internal
view
returns (uint256)
{
// Get valuation of the SetToken with the quote asset as the reserve asset. Returns value in precise units (10e18)
// Reverts if price is not found
uint256 setTokenValuation = _getSetValuer(_setToken).calculateSetTokenValuation(_setToken, _reserveAsset);
uint256 totalRedeemValueInPreciseUnits = _setTokenQuantity.preciseMul(setTokenValuation);
// Get reserve asset decimals
uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals();
uint256 prePremiumReserveQuantity = totalRedeemValueInPreciseUnits.preciseMul(10 ** reserveAssetDecimals);
uint256 premiumPercentage = _getRedeemPremium(_setToken, _reserveAsset, _setTokenQuantity);
uint256 premiumQuantity = prePremiumReserveQuantity.preciseMulCeil(premiumPercentage);
return prePremiumReserveQuantity.sub(premiumQuantity);
}
/**
* The new position multiplier is calculated as follows:
* inflationPercentage = (newSupply - oldSupply) / newSupply
* newMultiplier = (1 - inflationPercentage) * positionMultiplier
*/
function _getIssuePositionMultiplier(
ISetToken _setToken,
ActionInfo memory _issueInfo
)
internal
view
returns (uint256, int256)
{
// Calculate inflation and new position multiplier. Note: Round inflation up in order to round position multiplier down
uint256 newTotalSupply = _issueInfo.setTokenQuantity.add(_issueInfo.previousSetTokenSupply);
int256 newPositionMultiplier = _setToken.positionMultiplier()
.mul(_issueInfo.previousSetTokenSupply.toInt256())
.div(newTotalSupply.toInt256());
return (newTotalSupply, newPositionMultiplier);
}
/**
* Calculate deflation and new position multiplier. Note: Round deflation down in order to round position multiplier down
*
* The new position multiplier is calculated as follows:
* deflationPercentage = (oldSupply - newSupply) / newSupply
* newMultiplier = (1 + deflationPercentage) * positionMultiplier
*/
function _getRedeemPositionMultiplier(
ISetToken _setToken,
uint256 _setTokenQuantity,
ActionInfo memory _redeemInfo
)
internal
view
returns (uint256, int256)
{
uint256 newTotalSupply = _redeemInfo.previousSetTokenSupply.sub(_setTokenQuantity);
int256 newPositionMultiplier = _setToken.positionMultiplier()
.mul(_redeemInfo.previousSetTokenSupply.toInt256())
.div(newTotalSupply.toInt256());
return (newTotalSupply, newPositionMultiplier);
}
/**
* The new position reserve asset unit is calculated as follows:
* totalReserve = (oldUnit * oldSetTokenSupply) + reserveQuantity
* newUnit = totalReserve / newSetTokenSupply
*/
function _getIssuePositionUnit(
ISetToken _setToken,
address _reserveAsset,
ActionInfo memory _issueInfo
)
internal
view
returns (uint256)
{
uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256();
uint256 totalReserve = existingUnit
.preciseMul(_issueInfo.previousSetTokenSupply)
.add(_issueInfo.netFlowQuantity);
return totalReserve.preciseDiv(_issueInfo.newSetTokenSupply);
}
/**
* The new position reserve asset unit is calculated as follows:
* totalReserve = (oldUnit * oldSetTokenSupply) - reserveQuantityToSendOut
* newUnit = totalReserve / newSetTokenSupply
*/
function _getRedeemPositionUnit(
ISetToken _setToken,
address _reserveAsset,
ActionInfo memory _redeemInfo
)
internal
view
returns (uint256)
{
uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256();
uint256 totalExistingUnits = existingUnit.preciseMul(_redeemInfo.previousSetTokenSupply);
uint256 outflow = _redeemInfo.netFlowQuantity.add(_redeemInfo.protocolFees).add(_redeemInfo.managerFee);
// Require withdrawable quantity is greater than existing collateral
require(totalExistingUnits >= outflow, "Must be greater than total available collateral");
return totalExistingUnits.sub(outflow).preciseDiv(_redeemInfo.newSetTokenSupply);
}
/**
* If a pre-issue hook has been configured, call the external-protocol contract. Pre-issue hook logic
* can contain arbitrary logic including validations, external function calls, etc.
*/
function _callPreIssueHooks(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity,
address _caller,
address _to
)
internal
{
INAVIssuanceHook preIssueHook = navIssuanceSettings[_setToken].managerIssuanceHook;
if (address(preIssueHook) != address(0)) {
preIssueHook.invokePreIssueHook(_setToken, _reserveAsset, _reserveAssetQuantity, _caller, _to);
}
}
/**
* If a pre-redeem hook has been configured, call the external-protocol contract.
*/
function _callPreRedeemHooks(ISetToken _setToken, uint256 _setQuantity, address _caller, address _to) internal {
INAVIssuanceHook preRedeemHook = navIssuanceSettings[_setToken].managerRedemptionHook;
if (address(preRedeemHook) != address(0)) {
preRedeemHook.invokePreRedeemHook(_setToken, _setQuantity, _caller, _to);
}
}
/**
* If a custom set valuer has been configured, use it. Otherwise fetch the default one form the
* controller.
*/
function _getSetValuer(ISetToken _setToken) internal view returns (ISetValuer) {
ISetValuer customValuer = navIssuanceSettings[_setToken].setValuer;
return address(customValuer) == address(0) ? controller.getSetValuer() : customValuer;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*/
library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* @param A The input array to search
* @param a The address to remove
*/
function removeStorage(address[] storage A, address a)
internal
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here
if (index != lastIndex) { A[index] = A[lastIndex]; }
A.pop();
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
interface IController {
function addSet(address _setToken) external;
function feeRecipient() external view returns(address);
function getModuleFee(address _module, uint256 _feeType) external view returns(uint256);
function isModule(address _module) external view returns(bool);
function isSet(address _setToken) external view returns(bool);
function isSystemContract(address _contractAddress) external view returns (bool);
function resourceId(uint256 _id) external view returns(address);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { ISetToken } from "../interfaces/ISetToken.sol";
interface ISetValuer {
function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { ISetToken } from "./ISetToken.sol";
interface INAVIssuanceHook {
function invokePreIssueHook(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity,
address _sender,
address _to
)
external;
function invokePreRedeemHook(
ISetToken _setToken,
uint256 _redeemQuantity,
address _sender,
address _to
)
external;
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
/**
* @title Invoke
* @author Set Protocol
*
* A collection of common utility functions for interacting with the SetToken's invoke function
*/
library Invoke {
using SafeMath for uint256;
/* ============ Internal ============ */
/**
* Instructs the SetToken to set approvals of the ERC20 token to a spender.
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to approve
* @param _spender The account allowed to spend the SetToken's balance
* @param _quantity The quantity of allowance to allow
*/
function invokeApprove(
ISetToken _setToken,
address _token,
address _spender,
uint256 _quantity
)
internal
{
bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity);
_setToken.invoke(_token, 0, callData);
}
/**
* Instructs the SetToken to transfer the ERC20 token to a recipient.
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function invokeTransfer(
ISetToken _setToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity);
_setToken.invoke(_token, 0, callData);
}
}
/**
* Instructs the SetToken to transfer the ERC20 token to a recipient.
* The new SetToken balance must equal the existing balance less the quantity transferred
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function strictInvokeTransfer(
ISetToken _setToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
// Retrieve current balance of token for the SetToken
uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken));
Invoke.invokeTransfer(_setToken, _token, _to, _quantity);
// Get new balance of transferred token for SetToken
uint256 newBalance = IERC20(_token).balanceOf(address(_setToken));
// Verify only the transfer quantity is subtracted
require(
newBalance == existingBalance.sub(_quantity),
"Invalid post transfer balance"
);
}
}
/**
* Instructs the SetToken to unwrap the passed quantity of WETH
*
* @param _setToken SetToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeUnwrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity);
_setToken.invoke(_weth, 0, callData);
}
/**
* Instructs the SetToken to wrap the passed quantity of ETH
*
* @param _setToken SetToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("deposit()");
_setToken.invoke(_weth, _quantity, callData);
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ISetToken
* @author Set Protocol
*
* Interface for operating with SetTokens.
*/
interface ISetToken is IERC20 {
/* ============ Enums ============ */
enum ModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ */
/**
* The base definition of a SetToken Position
*
* @param component Address of token in the Position
* @param module If not in default state, the address of associated module
* @param unit Each unit is the # of components per 10^18 of a SetToken
* @param positionState Position ENUM. Default is 0; External is 1
* @param data Arbitrary data
*/
struct Position {
address component;
address module;
int256 unit;
uint8 positionState;
bytes data;
}
/**
* A struct that stores a component's cash position details and external positions
* This data structure allows O(1) access to a component's cash position units and
* virtual units.
*
* @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency
* updating all units at once via the position multiplier. Virtual units are achieved
* by dividing a "real" value by the "positionMultiplier"
* @param componentIndex
* @param externalPositionModules List of external modules attached to each external position. Each module
* maps to an external position
* @param externalPositions Mapping of module => ExternalPosition struct for a given component
*/
struct ComponentPosition {
int256 virtualUnit;
address[] externalPositionModules;
mapping(address => ExternalPosition) externalPositions;
}
/**
* A struct that stores a component's external position details including virtual unit and any
* auxiliary data.
*
* @param virtualUnit Virtual value of a component's EXTERNAL position.
* @param data Arbitrary data
*/
struct ExternalPosition {
int256 virtualUnit;
bytes data;
}
/* ============ Functions ============ */
function addComponent(address _component) external;
function removeComponent(address _component) external;
function editDefaultPositionUnit(address _component, int256 _realUnit) external;
function addExternalPositionModule(address _component, address _positionModule) external;
function removeExternalPositionModule(address _component, address _positionModule) external;
function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;
function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);
function editPositionMultiplier(int256 _newMultiplier) external;
function mint(address _account, uint256 _quantity) external;
function burn(address _account, uint256 _quantity) external;
function lock() external;
function unlock() external;
function addModule(address _module) external;
function removeModule(address _module) external;
function initializeModule() external;
function setManager(address _manager) external;
function manager() external view returns (address);
function moduleStates(address _module) external view returns (ModuleState);
function getModules() external view returns (address[] memory);
function getDefaultPositionRealUnit(address _component) external view returns(int256);
function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);
function getComponents() external view returns(address[] memory);
function getExternalPositionModules(address _component) external view returns(address[] memory);
function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);
function isExternalPositionModule(address _component, address _module) external view returns(bool);
function isComponent(address _component) external view returns(bool);
function positionMultiplier() external view returns (int256);
function getPositions() external view returns (Position[] memory);
function getTotalComponentRealUnits(address _component) external view returns(int256);
function isInitializedModule(address _module) external view returns(bool);
function isPendingModule(address _module) external view returns(bool);
function isLocked() external view returns (bool);
}
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title IWETH
* @author Set Protocol
*
* Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal
* functionality.
*/
interface IWETH is IERC20{
function deposit()
external
payable;
function withdraw(
uint256 wad
)
external;
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol";
import { ExplicitERC20 } from "../../lib/ExplicitERC20.sol";
import { IController } from "../../interfaces/IController.sol";
import { IModule } from "../../interfaces/IModule.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { Invoke } from "./Invoke.sol";
import { Position } from "./Position.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
import { ResourceIdentifier } from "./ResourceIdentifier.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title ModuleBase
* @author Set Protocol
*
* Abstract class that houses common Module-related state and functions.
*/
abstract contract ModuleBase is IModule {
using AddressArrayUtils for address[];
using Invoke for ISetToken;
using Position for ISetToken;
using PreciseUnitMath for uint256;
using ResourceIdentifier for IController;
using SafeCast for int256;
using SafeCast for uint256;
using SafeMath for uint256;
using SignedSafeMath for int256;
/* ============ State Variables ============ */
// Address of the controller
IController public controller;
/* ============ Modifiers ============ */
modifier onlyManagerAndValidSet(ISetToken _setToken) {
require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager");
require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken");
_;
}
modifier onlySetManager(ISetToken _setToken, address _caller) {
require(isSetManager(_setToken, _caller), "Must be the SetToken manager");
_;
}
modifier onlyValidAndInitializedSet(ISetToken _setToken) {
require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken");
_;
}
/**
* Throws if the sender is not a SetToken's module or module not enabled
*/
modifier onlyModule(ISetToken _setToken) {
require(
_setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED,
"Only the module can call"
);
require(
controller.isModule(msg.sender),
"Module must be enabled on controller"
);
_;
}
/**
* Utilized during module initializations to check that the module is in pending state
* and that the SetToken is valid
*/
modifier onlyValidAndPendingSet(ISetToken _setToken) {
require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken");
require(isSetPendingInitialization(_setToken), "Must be pending initialization");
_;
}
/* ============ Constructor ============ */
/**
* Set state variables and map asset pairs to their oracles
*
* @param _controller Address of controller contract
*/
constructor(IController _controller) public {
controller = _controller;
}
/* ============ Internal Functions ============ */
/**
* Transfers tokens from an address (that has set allowance on the module).
*
* @param _token The address of the ERC20 token
* @param _from The address to transfer from
* @param _to The address to transfer to
* @param _quantity The number of tokens to transfer
*/
function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal {
ExplicitERC20.transferFrom(_token, _from, _to, _quantity);
}
/**
* Gets the integration for the module with the passed in name. Validates that the address is not empty
*/
function getAndValidateAdapter(string memory _integrationName) internal view returns(address) {
bytes32 integrationHash = getNameHash(_integrationName);
return getAndValidateAdapterWithHash(integrationHash);
}
/**
* Gets the integration for the module with the passed in hash. Validates that the address is not empty
*/
function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) {
address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash(
address(this),
_integrationHash
);
require(adapter != address(0), "Must be valid adapter");
return adapter;
}
/**
* Gets the total fee for this module of the passed in index (fee % * quantity)
*/
function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) {
uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex);
return _quantity.preciseMul(feePercentage);
}
/**
* Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient
*/
function payProtocolFeeFromSetToken(ISetToken _setToken, address _token, uint256 _feeQuantity) internal {
if (_feeQuantity > 0) {
_setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity);
}
}
/**
* Returns true if the module is in process of initialization on the SetToken
*/
function isSetPendingInitialization(ISetToken _setToken) internal view returns(bool) {
return _setToken.isPendingModule(address(this));
}
/**
* Returns true if the address is the SetToken's manager
*/
function isSetManager(ISetToken _setToken, address _toCheck) internal view returns(bool) {
return _setToken.manager() == _toCheck;
}
/**
* Returns true if SetToken must be enabled on the controller
* and module is registered on the SetToken
*/
function isSetValidAndInitialized(ISetToken _setToken) internal view returns(bool) {
return controller.isSet(address(_setToken)) &&
_setToken.isInitializedModule(address(this));
}
/**
* Hashes the string and returns a bytes32 value
*/
function getNameHash(string memory _name) internal pure returns(bytes32) {
return keccak256(bytes(_name));
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
/**
* @title Position
* @author Set Protocol
*
* Collection of helper functions for handling and updating SetToken Positions
*
* CHANGELOG:
* - Updated editExternalPosition to work when no external position is associated with module
*/
library Position {
using SafeCast for uint256;
using SafeMath for uint256;
using SafeCast for int256;
using SignedSafeMath for int256;
using PreciseUnitMath for uint256;
/* ============ Helper ============ */
/**
* Returns whether the SetToken has a default position for a given component (if the real unit is > 0)
*/
function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) {
return _setToken.getDefaultPositionRealUnit(_component) > 0;
}
/**
* Returns whether the SetToken has an external position for a given component (if # of position modules is > 0)
*/
function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) {
return _setToken.getExternalPositionModules(_component).length > 0;
}
/**
* Returns whether the SetToken component default position real unit is greater than or equal to units passed in.
*/
function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) {
return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256();
}
/**
* Returns whether the SetToken component external position is greater than or equal to the real units passed in.
*/
function hasSufficientExternalUnits(
ISetToken _setToken,
address _component,
address _positionModule,
uint256 _unit
)
internal
view
returns(bool)
{
return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256();
}
/**
* If the position does not exist, create a new Position and add to the SetToken. If it already exists,
* then set the position units. If the new units is 0, remove the position. Handles adding/removing of
* components where needed (in light of potential external positions).
*
* @param _setToken Address of SetToken being modified
* @param _component Address of the component
* @param _newUnit Quantity of Position units - must be >= 0
*/
function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal {
bool isPositionFound = hasDefaultPosition(_setToken, _component);
if (!isPositionFound && _newUnit > 0) {
// If there is no Default Position and no External Modules, then component does not exist
if (!hasExternalPosition(_setToken, _component)) {
_setToken.addComponent(_component);
}
} else if (isPositionFound && _newUnit == 0) {
// If there is a Default Position and no external positions, remove the component
if (!hasExternalPosition(_setToken, _component)) {
_setToken.removeComponent(_component);
}
}
_setToken.editDefaultPositionUnit(_component, _newUnit.toInt256());
}
/**
* Update an external position and remove and external positions or components if necessary. The logic flows as follows:
* 1) If component is not already added then add component and external position.
* 2) If component is added but no existing external position using the passed module exists then add the external position.
* 3) If the existing position is being added to then just update the unit and data
* 4) If the position is being closed and no other external positions or default positions are associated with the component
* then untrack the component and remove external position.
* 5) If the position is being closed and other existing positions still exist for the component then just remove the
* external position.
*
* @param _setToken SetToken being updated
* @param _component Component position being updated
* @param _module Module external position is associated with
* @param _newUnit Position units of new external position
* @param _data Arbitrary data associated with the position
*/
function editExternalPosition(
ISetToken _setToken,
address _component,
address _module,
int256 _newUnit,
bytes memory _data
)
internal
{
if (_newUnit != 0) {
if (!_setToken.isComponent(_component)) {
_setToken.addComponent(_component);
_setToken.addExternalPositionModule(_component, _module);
} else if (!_setToken.isExternalPositionModule(_component, _module)) {
_setToken.addExternalPositionModule(_component, _module);
}
_setToken.editExternalPositionUnit(_component, _module, _newUnit);
_setToken.editExternalPositionData(_component, _module, _data);
} else {
require(_data.length == 0, "Passed data must be null");
// If no default or external position remaining then remove component from components array
if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) {
address[] memory positionModules = _setToken.getExternalPositionModules(_component);
if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) {
require(positionModules[0] == _module, "External positions must be 0 to remove component");
_setToken.removeComponent(_component);
}
_setToken.removeExternalPositionModule(_component, _module);
}
}
}
/**
* Get total notional amount of Default position
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _positionUnit Quantity of Position units
*
* @return Total notional amount of units
*/
function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) {
return _setTokenSupply.preciseMul(_positionUnit);
}
/**
* Get position unit from total notional amount
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _totalNotional Total notional amount of component prior to
* @return Default position unit
*/
function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) {
return _totalNotional.preciseDiv(_setTokenSupply);
}
/**
* Get the total tracked balance - total supply * position unit
*
* @param _setToken Address of the SetToken
* @param _component Address of the component
* @return Notional tracked balance
*/
function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) {
int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component);
return _setToken.totalSupply().preciseMul(positionUnit.toUint256());
}
/**
* Calculates the new default position unit and performs the edit with the new unit
*
* @param _setToken Address of the SetToken
* @param _component Address of the component
* @param _setTotalSupply Current SetToken supply
* @param _componentPreviousBalance Pre-action component balance
* @return Current component balance
* @return Previous position unit
* @return New position unit
*/
function calculateAndEditDefaultPosition(
ISetToken _setToken,
address _component,
uint256 _setTotalSupply,
uint256 _componentPreviousBalance
)
internal
returns(uint256, uint256, uint256)
{
uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken));
uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256();
uint256 newTokenUnit;
if (currentBalance > 0) {
newTokenUnit = calculateDefaultEditPositionUnit(
_setTotalSupply,
_componentPreviousBalance,
currentBalance,
positionUnit
);
} else {
newTokenUnit = 0;
}
editDefaultPosition(_setToken, _component, newTokenUnit);
return (currentBalance, positionUnit, newTokenUnit);
}
/**
* Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state
* The intention is to make updates to the units without accidentally picking up airdropped assets as well.
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _preTotalNotional Total notional amount of component prior to executing action
* @param _postTotalNotional Total notional amount of component after the executing action
* @param _prePositionUnit Position unit of SetToken prior to executing action
* @return New position unit
*/
function calculateDefaultEditPositionUnit(
uint256 _setTokenSupply,
uint256 _preTotalNotional,
uint256 _postTotalNotional,
uint256 _prePositionUnit
)
internal
pure
returns (uint256)
{
// If pre action total notional amount is greater then subtract post action total notional and calculate new position units
uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_setTokenSupply));
return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_setTokenSupply);
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title PreciseUnitMath
* @author Set Protocol
*
* Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from
* dYdX's BaseMath library.
*
* CHANGELOG:
* - 9/21/20: Added safePower function
*/
library PreciseUnitMath {
using SafeMath for uint256;
using SignedSafeMath for int256;
// The number One in precise units.
uint256 constant internal PRECISE_UNIT = 10 ** 18;
int256 constant internal PRECISE_UNIT_INT = 10 ** 18;
// Max unsigned integer value
uint256 constant internal MAX_UINT_256 = type(uint256).max;
// Max and min signed integer value
int256 constant internal MAX_INT_256 = type(int256).max;
int256 constant internal MIN_INT_256 = type(int256).min;
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnit() internal pure returns (uint256) {
return PRECISE_UNIT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnitInt() internal pure returns (int256) {
return PRECISE_UNIT_INT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxUint256() internal pure returns (uint256) {
return MAX_UINT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxInt256() internal pure returns (int256) {
return MAX_INT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function minInt256() internal pure returns (int256) {
return MIN_INT_256;
}
/**
* @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(b).div(PRECISE_UNIT);
}
/**
* @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the
* significand of a number with 18 decimals precision.
*/
function preciseMul(int256 a, int256 b) internal pure returns (int256) {
return a.mul(b).div(PRECISE_UNIT_INT);
}
/**
* @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
return a.mul(b).sub(1).div(PRECISE_UNIT).add(1);
}
/**
* @dev Divides value a by value b (result is rounded down).
*/
function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(PRECISE_UNIT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded towards 0).
*/
function preciseDiv(int256 a, int256 b) internal pure returns (int256) {
return a.mul(PRECISE_UNIT_INT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded up or away from 0).
*/
function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "Cant divide by 0");
return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0;
}
/**
* @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0).
*/
function divDown(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "Cant divide by 0");
require(a != MIN_INT_256 || b != -1, "Invalid input");
int256 result = a.div(b);
if (a ^ b < 0 && a % b != 0) {
result -= 1;
}
return result;
}
/**
* @dev Multiplies value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(b), PRECISE_UNIT_INT);
}
/**
* @dev Divides value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(PRECISE_UNIT_INT), b);
}
/**
* @dev Performs the power on a specified value, reverts on overflow.
*/
function safePower(
uint256 a,
uint256 pow
)
internal
pure
returns (uint256)
{
require(a > 0, "Value must be positive");
uint256 result = 1;
for (uint256 i = 0; i < pow; i++){
uint256 previousResult = result;
// Using safemath multiplication prevents overflows
result = previousResult.mul(a);
}
return result;
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IController } from "../../interfaces/IController.sol";
import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol";
import { IPriceOracle } from "../../interfaces/IPriceOracle.sol";
import { ISetValuer } from "../../interfaces/ISetValuer.sol";
/**
* @title ResourceIdentifier
* @author Set Protocol
*
* A collection of utility functions to fetch information related to Resource contracts in the system
*/
library ResourceIdentifier {
// IntegrationRegistry will always be resource ID 0 in the system
uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0;
// PriceOracle will always be resource ID 1 in the system
uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1;
// SetValuer resource will always be resource ID 2 in the system
uint256 constant internal SET_VALUER_RESOURCE_ID = 2;
/* ============ Internal ============ */
/**
* Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on
* the Controller
*/
function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) {
return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID));
}
/**
* Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller
*/
function getPriceOracle(IController _controller) internal view returns (IPriceOracle) {
return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID));
}
/**
* Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller
*/
function getSetValuer(IController _controller) internal view returns (ISetValuer) {
return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title ExplicitERC20
* @author Set Protocol
*
* Utility functions for ERC20 transfers that require the explicit amount to be transferred.
*/
library ExplicitERC20 {
using SafeMath for uint256;
/**
* When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity".
* Ensures that the recipient has received the correct quantity (ie no fees taken on transfer)
*
* @param _token ERC20 token to approve
* @param _from The account to transfer tokens from
* @param _to The account to transfer tokens to
* @param _quantity The quantity to transfer
*/
function transferFrom(
IERC20 _token,
address _from,
address _to,
uint256 _quantity
)
internal
{
// Call specified ERC20 contract to transfer tokens (via proxy).
if (_quantity > 0) {
uint256 existingBalance = _token.balanceOf(_to);
SafeERC20.safeTransferFrom(
_token,
_from,
_to,
_quantity
);
uint256 newBalance = _token.balanceOf(_to);
// Verify transfer quantity is reflected in balance
require(
newBalance == existingBalance.add(_quantity),
"Invalid post transfer balance"
);
}
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title IModule
* @author Set Protocol
*
* Interface for interacting with Modules.
*/
interface IModule {
/**
* Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included
* in case checks need to be made or state needs to be cleared.
*/
function removeModule() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
interface IIntegrationRegistry {
function addIntegration(address _module, string memory _id, address _wrapper) external;
function getIntegrationAdapter(address _module, string memory _id) external view returns(address);
function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address);
function isValidIntegration(address _module, string memory _id) external view returns(bool);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title IPriceOracle
* @author Set Protocol
*
* Interface for interacting with PriceOracle
*/
interface IPriceOracle {
/* ============ Functions ============ */
function getPrice(address _assetOne, address _assetTwo) external view returns (uint256);
function masterQuoteAsset() external view returns (address);
}
|
Returns true if there are 2 elements that are the same in an array A The input array to search return Returns boolean for the first occurrence of a duplicate/
|
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
| 91,253 |
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {EnumerableSet} from "@solidstate/contracts/utils/EnumerableSet.sol";
import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol";
import {IPoolIO} from "./IPoolIO.sol";
import {PoolSwap} from "./PoolSwap.sol";
import {PoolStorage} from "./PoolStorage.sol";
import {IPremiaMining} from "../mining/IPremiaMining.sol";
/**
* @title Premia option pool
* @dev deployed standalone and referenced by PoolProxy
*/
contract PoolIO is IPoolIO, PoolSwap {
using ABDKMath64x64 for int128;
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using PoolStorage for PoolStorage.Layout;
constructor(
address ivolOracle,
address weth,
address premiaMining,
address feeReceiver,
address feeDiscountAddress,
int128 fee64x64,
address uniswapV2Factory,
address sushiswapFactory
)
PoolSwap(
ivolOracle,
weth,
premiaMining,
feeReceiver,
feeDiscountAddress,
fee64x64,
uniswapV2Factory,
sushiswapFactory
)
{}
/**
* @inheritdoc IPoolIO
*/
function setDivestmentTimestamp(uint64 timestamp, bool isCallPool)
external
override
{
PoolStorage.Layout storage l = PoolStorage.layout();
require(
timestamp >= l.depositedAt[msg.sender][isCallPool] + (1 days),
"liq lock 1d"
);
l.divestmentTimestamps[msg.sender][isCallPool] = timestamp;
}
/**
* @inheritdoc IPoolIO
*/
function deposit(uint256 amount, bool isCallPool)
external
payable
override
{
_deposit(amount, isCallPool, false);
}
/**
* @inheritdoc IPoolIO
*/
function swapAndDeposit(
uint256 amount,
bool isCallPool,
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
bool isSushi
) external payable override {
// If value is passed, amountInMax must be 0, as the value wont be used
// If amountInMax is not 0, user wants to do a swap from an ERC20, and therefore no value should be attached
require(
msg.value == 0 || amountInMax == 0,
"value and amountInMax passed"
);
// If no amountOut has been passed, we swap the exact deposit amount specified
if (amountOut == 0) {
amountOut = amount;
}
if (msg.value > 0) {
_swapETHForExactTokens(amountOut, path, isSushi);
} else {
_swapTokensForExactTokens(amountOut, amountInMax, path, isSushi);
}
_deposit(amount, isCallPool, true);
}
/**
* @inheritdoc IPoolIO
*/
function withdraw(uint256 amount, bool isCallPool) public override {
PoolStorage.Layout storage l = PoolStorage.layout();
uint256 toWithdraw = amount;
_processPendingDeposits(l, isCallPool);
uint256 depositedAt = l.depositedAt[msg.sender][isCallPool];
require(depositedAt + (1 days) < block.timestamp, "liq lock 1d");
int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCallPool);
{
uint256 reservedLiqTokenId = _getReservedLiquidityTokenId(
isCallPool
);
uint256 reservedLiquidity = _balanceOf(
msg.sender,
reservedLiqTokenId
);
if (reservedLiquidity > 0) {
uint256 reservedLiqToWithdraw;
if (reservedLiquidity < toWithdraw) {
reservedLiqToWithdraw = reservedLiquidity;
} else {
reservedLiqToWithdraw = toWithdraw;
}
toWithdraw -= reservedLiqToWithdraw;
// burn reserved liquidity tokens from sender
_burn(msg.sender, reservedLiqTokenId, reservedLiqToWithdraw);
}
}
if (toWithdraw > 0) {
// burn free liquidity tokens from sender
_burn(msg.sender, _getFreeLiquidityTokenId(isCallPool), toWithdraw);
int128 newLiquidity64x64 = l.totalFreeLiquiditySupply64x64(
isCallPool
);
_setCLevel(l, oldLiquidity64x64, newLiquidity64x64, isCallPool);
}
_subUserTVL(l, msg.sender, isCallPool, amount);
_pushTo(msg.sender, _getPoolToken(isCallPool), amount);
emit Withdrawal(msg.sender, isCallPool, depositedAt, amount);
}
/**
* @inheritdoc IPoolIO
*/
function reassign(uint256 tokenId, uint256 contractSize)
external
override
returns (
uint256 baseCost,
uint256 feeCost,
uint256 amountOut
)
{
PoolStorage.Layout storage l = PoolStorage.layout();
int128 newPrice64x64 = _update(l);
(
PoolStorage.TokenType tokenType,
uint64 maturity,
int128 strike64x64
) = PoolStorage.parseTokenId(tokenId);
bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL ||
tokenType == PoolStorage.TokenType.LONG_CALL;
(baseCost, feeCost, amountOut) = _reassign(
l,
msg.sender,
maturity,
strike64x64,
isCall,
contractSize,
newPrice64x64
);
_pushTo(msg.sender, _getPoolToken(isCall), amountOut);
}
/**
* @inheritdoc IPoolIO
*/
function reassignBatch(
uint256[] calldata tokenIds,
uint256[] calldata contractSizes
)
public
override
returns (
uint256[] memory baseCosts,
uint256[] memory feeCosts,
uint256 amountOutCall,
uint256 amountOutPut
)
{
require(tokenIds.length == contractSizes.length, "diff array length");
PoolStorage.Layout storage l = PoolStorage.layout();
int128 newPrice64x64 = _update(l);
baseCosts = new uint256[](tokenIds.length);
feeCosts = new uint256[](tokenIds.length);
for (uint256 i; i < tokenIds.length; i++) {
(
PoolStorage.TokenType tokenType,
uint64 maturity,
int128 strike64x64
) = PoolStorage.parseTokenId(tokenIds[i]);
bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL ||
tokenType == PoolStorage.TokenType.LONG_CALL;
uint256 amountOut;
uint256 contractSize = contractSizes[i];
(baseCosts[i], feeCosts[i], amountOut) = _reassign(
l,
msg.sender,
maturity,
strike64x64,
isCall,
contractSize,
newPrice64x64
);
if (isCall) {
amountOutCall += amountOut;
} else {
amountOutPut += amountOut;
}
}
_pushTo(msg.sender, _getPoolToken(true), amountOutCall);
_pushTo(msg.sender, _getPoolToken(false), amountOutPut);
}
/**
* @inheritdoc IPoolIO
*/
function withdrawAllAndReassignBatch(
bool isCallPool,
uint256[] calldata tokenIds,
uint256[] calldata contractSizes
)
external
override
returns (
uint256[] memory baseCosts,
uint256[] memory feeCosts,
uint256 amountOutCall,
uint256 amountOutPut
)
{
uint256 balance = _balanceOf(
msg.sender,
_getFreeLiquidityTokenId(isCallPool)
);
if (balance > 0) {
withdraw(balance, isCallPool);
}
(baseCosts, feeCosts, amountOutCall, amountOutPut) = reassignBatch(
tokenIds,
contractSizes
);
}
/**
* @inheritdoc IPoolIO
*/
function withdrawFees()
external
override
returns (uint256 amountOutCall, uint256 amountOutPut)
{
amountOutCall = _withdrawFees(true);
amountOutPut = _withdrawFees(false);
_pushTo(FEE_RECEIVER_ADDRESS, _getPoolToken(true), amountOutCall);
_pushTo(FEE_RECEIVER_ADDRESS, _getPoolToken(false), amountOutPut);
}
/**
* @inheritdoc IPoolIO
*/
function annihilate(uint256 tokenId, uint256 contractSize)
external
override
{
(
PoolStorage.TokenType tokenType,
uint64 maturity,
int128 strike64x64
) = PoolStorage.parseTokenId(tokenId);
bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL ||
tokenType == PoolStorage.TokenType.LONG_CALL;
_annihilate(msg.sender, maturity, strike64x64, isCall, contractSize);
_pushTo(
msg.sender,
_getPoolToken(isCall),
isCall
? contractSize
: PoolStorage.layout().fromUnderlyingToBaseDecimals(
strike64x64.mulu(contractSize)
)
);
}
/**
* @inheritdoc IPoolIO
*/
function claimRewards(bool isCallPool) external override {
claimRewards(msg.sender, isCallPool);
}
/**
* @inheritdoc IPoolIO
*/
function claimRewards(address account, bool isCallPool) public override {
PoolStorage.Layout storage l = PoolStorage.layout();
uint256 userTVL = l.userTVL[account][isCallPool];
uint256 totalTVL = l.totalTVL[isCallPool];
IPremiaMining(PREMIA_MINING_ADDRESS).claim(
account,
address(this),
isCallPool,
userTVL,
userTVL,
totalTVL
);
}
/**
* @inheritdoc IPoolIO
*/
function updateMiningPools() external override {
PoolStorage.Layout storage l = PoolStorage.layout();
IPremiaMining(PREMIA_MINING_ADDRESS).updatePool(
address(this),
true,
l.totalTVL[true]
);
IPremiaMining(PREMIA_MINING_ADDRESS).updatePool(
address(this),
false,
l.totalTVL[false]
);
}
/**
* @notice deposit underlying currency, underwriting calls of that currency with respect to base currency
* @param amount quantity of underlying currency to deposit
* @param isCallPool whether to deposit underlying in the call pool or base in the put pool
* @param skipWethDeposit if false, will not try to deposit weth from attach eth
*/
function _deposit(
uint256 amount,
bool isCallPool,
bool skipWethDeposit
) internal {
PoolStorage.Layout storage l = PoolStorage.layout();
// Reset gradual divestment timestamp
delete l.divestmentTimestamps[msg.sender][isCallPool];
uint256 cap = _getPoolCapAmount(l, isCallPool);
require(
l.totalTVL[isCallPool] + amount <= cap,
"pool deposit cap reached"
);
_processPendingDeposits(l, isCallPool);
l.depositedAt[msg.sender][isCallPool] = block.timestamp;
_addUserTVL(l, msg.sender, isCallPool, amount);
_pullFrom(
msg.sender,
_getPoolToken(isCallPool),
amount,
skipWethDeposit
);
_addToDepositQueue(msg.sender, amount, isCallPool);
emit Deposit(msg.sender, isCallPool, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Set implementation with enumeration functions
* @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts (MIT license)
*/
library EnumerableSet {
struct Set {
bytes32[] _values;
// 1-indexed to allow 0 to signify nonexistence
mapping(bytes32 => uint256) _indexes;
}
struct Bytes32Set {
Set _inner;
}
struct AddressSet {
Set _inner;
}
struct UintSet {
Set _inner;
}
function at(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return _at(set._inner, index);
}
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return address(uint160(uint256(_at(set._inner, index))));
}
function at(UintSet storage set, uint256 index)
internal
view
returns (uint256)
{
return uint256(_at(set._inner, index));
}
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return _contains(set._inner, value);
}
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
function contains(UintSet storage set, uint256 value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(value));
}
function indexOf(Bytes32Set storage set, bytes32 value)
internal
view
returns (uint256)
{
return _indexOf(set._inner, value);
}
function indexOf(AddressSet storage set, address value)
internal
view
returns (uint256)
{
return _indexOf(set._inner, bytes32(uint256(uint160(value))));
}
function indexOf(UintSet storage set, uint256 value)
internal
view
returns (uint256)
{
return _indexOf(set._inner, bytes32(value));
}
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function add(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _add(set._inner, value);
}
function add(AddressSet storage set, address value)
internal
returns (bool)
{
return _add(set._inner, bytes32(uint256(uint160(value))));
}
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
function remove(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _remove(set._inner, value);
}
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
function remove(UintSet storage set, uint256 value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(value));
}
function _at(Set storage set, uint256 index)
private
view
returns (bytes32)
{
require(
set._values.length > index,
'EnumerableSet: index out of bounds'
);
return set._values[index];
}
function _contains(Set storage set, bytes32 value)
private
view
returns (bool)
{
return set._indexes[value] != 0;
}
function _indexOf(Set storage set, bytes32 value)
private
view
returns (uint256)
{
unchecked {
return set._indexes[value] - 1;
}
}
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _remove(Set storage set, bytes32 value) private returns (bool) {
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint256 index = valueIndex - 1;
bytes32 last = set._values[set._values.length - 1];
// move last value to now-vacant index
set._values[index] = last;
set._indexes[last] = index + 1;
// clear last index
set._values.pop();
delete set._indexes[value];
return true;
} else {
return false;
}
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.8.0;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
unchecked {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
unchecked {
return int64 (x >> 64);
}
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
unchecked {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (int256 (x << 64));
}
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
unchecked {
require (x >= 0);
return uint64 (uint128 (x >> 64));
}
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
unchecked {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
unchecked {
return int256 (x) << 64;
}
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul (int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
unchecked {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
unchecked {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (int256 (x)) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
unchecked {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
unchecked {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
unchecked {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
unchecked {
require (x != MIN_64x64);
return -x;
}
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
unchecked {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
unchecked {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
unchecked {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m)));
}
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
unchecked {
bool negative = x < 0 && y & 1 == 1;
uint256 absX = uint128 (x < 0 ? -x : x);
uint256 absResult;
absResult = 0x100000000000000000000000000000000;
if (absX <= 0x10000000000000000) {
absX <<= 63;
while (y != 0) {
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x2 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x4 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x8 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
y >>= 4;
}
absResult >>= 64;
} else {
uint256 absXShift = 63;
if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }
if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }
if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }
if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }
if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }
if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }
uint256 resultShift = 0;
while (y != 0) {
require (absXShift < 64);
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
resultShift += absXShift;
if (absResult > 0x100000000000000000000000000000000) {
absResult >>= 1;
resultShift += 1;
}
}
absX = absX * absX >> 127;
absXShift <<= 1;
if (absX >= 0x100000000000000000000000000000000) {
absX >>= 1;
absXShift += 1;
}
y >>= 1;
}
require (resultShift < 64);
absResult >>= 64 - resultShift;
}
int256 result = negative ? -int256 (absResult) : int256 (absResult);
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
unchecked {
require (x >= 0);
return int128 (sqrtu (uint256 (int256 (x)) << 64));
}
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
unchecked {
require (x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = msb - 64 << 64;
uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
unchecked {
require (x > 0);
return int128 (int256 (
uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));
}
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
unchecked {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= uint256 (int256 (63 - (x >> 64)));
require (result <= uint256 (int256 (MAX_64x64)));
return int128 (int256 (result));
}
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
unchecked {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
unchecked {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x) private pure returns (uint128) {
unchecked {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }
if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }
if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }
if (xx >= 0x10000) { xx >>= 16; r <<= 8; }
if (xx >= 0x100) { xx >>= 8; r <<= 4; }
if (xx >= 0x10) { xx >>= 4; r <<= 2; }
if (xx >= 0x8) { r <<= 1; }
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return uint128 (r < r1 ? r : r1);
}
}
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.0;
/**
* @notice Pool interface for LP position and platform fee management functions
*/
interface IPoolIO {
/**
* @notice set timestamp after which reinvestment is disabled
* @param timestamp timestamp to begin divestment
* @param isCallPool whether we set divestment timestamp for the call pool or put pool
*/
function setDivestmentTimestamp(uint64 timestamp, bool isCallPool) external;
/**
* @notice deposit underlying currency, underwriting calls of that currency with respect to base currency
* @param amount quantity of underlying currency to deposit
* @param isCallPool whether to deposit underlying in the call pool or base in the put pool
*/
function deposit(uint256 amount, bool isCallPool) external payable;
/**
* @notice deposit underlying currency, underwriting calls of that currency with respect to base currency
* @param amount quantity of underlying currency to deposit
* @param isCallPool whether to deposit underlying in the call pool or base in the put pool
* @param amountOut amount out of tokens requested. If 0, we will swap exact amount necessary to pay the quote
* @param amountInMax amount in max of tokens
* @param path swap path
* @param isSushi whether we use sushi or uniV2 for the swap
*/
function swapAndDeposit(
uint256 amount,
bool isCallPool,
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
bool isSushi
) external payable;
/**
* @notice redeem pool share tokens for underlying asset
* @param amount quantity of share tokens to redeem
* @param isCallPool whether to deposit underlying in the call pool or base in the put pool
*/
function withdraw(uint256 amount, bool isCallPool) external;
/**
* @notice reassign short position to new underwriter
* @param tokenId ERC1155 token id (long or short)
* @param contractSize quantity of option contract tokens to reassign
* @return baseCost quantity of tokens required to reassign short position
* @return feeCost quantity of tokens required to pay fees
* @return amountOut quantity of liquidity freed and transferred to owner
*/
function reassign(uint256 tokenId, uint256 contractSize)
external
returns (
uint256 baseCost,
uint256 feeCost,
uint256 amountOut
);
/**
* @notice reassign set of short position to new underwriter
* @param tokenIds array of ERC1155 token ids (long or short)
* @param contractSizes array of quantities of option contract tokens to reassign
* @return baseCosts quantities of tokens required to reassign each short position
* @return feeCosts quantities of tokens required to pay fees
* @return amountOutCall quantity of call pool liquidity freed and transferred to owner
* @return amountOutPut quantity of put pool liquidity freed and transferred to owner
*/
function reassignBatch(
uint256[] calldata tokenIds,
uint256[] calldata contractSizes
)
external
returns (
uint256[] memory baseCosts,
uint256[] memory feeCosts,
uint256 amountOutCall,
uint256 amountOutPut
);
/**
* @notice withdraw all free liquidity and reassign set of short position to new underwriter
* @param isCallPool true for call, false for put
* @param tokenIds array of ERC1155 token ids (long or short)
* @param contractSizes array of quantities of option contract tokens to reassign
* @return baseCosts quantities of tokens required to reassign each short position
* @return feeCosts quantities of tokens required to pay fees
* @return amountOutCall quantity of call pool liquidity freed and transferred to owner
* @return amountOutPut quantity of put pool liquidity freed and transferred to owner
*/
function withdrawAllAndReassignBatch(
bool isCallPool,
uint256[] calldata tokenIds,
uint256[] calldata contractSizes
)
external
returns (
uint256[] memory baseCosts,
uint256[] memory feeCosts,
uint256 amountOutCall,
uint256 amountOutPut
);
/**
* @notice transfer accumulated fees to the fee receiver
* @return amountOutCall quantity of underlying tokens transferred
* @return amountOutPut quantity of base tokens transferred
*/
function withdrawFees()
external
returns (uint256 amountOutCall, uint256 amountOutPut);
/**
* @notice burn corresponding long and short option tokens and withdraw collateral
* @param tokenId ERC1155 token id (long or short)
* @param contractSize quantity of option contract tokens to annihilate
*/
function annihilate(uint256 tokenId, uint256 contractSize) external;
/**
* @notice claim earned PREMIA emissions
* @param isCallPool true for call, false for put
*/
function claimRewards(bool isCallPool) external;
/**
* @notice claim earned PREMIA emissions on behalf of given account
* @param account account on whose behalf to claim rewards
* @param isCallPool true for call, false for put
*/
function claimRewards(address account, bool isCallPool) external;
/**
* @notice TODO
*/
function updateMiningPools() external;
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {PoolStorage} from "./PoolStorage.sol";
import {IWETH} from "@solidstate/contracts/utils/IWETH.sol";
import {IUniswapV2Pair} from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import {SafeERC20} from "@solidstate/contracts/utils/SafeERC20.sol";
import {IERC20} from "@solidstate/contracts/token/ERC20/IERC20.sol";
import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol";
import {PoolInternal} from "./PoolInternal.sol";
/**
* @title Premia option pool
* @dev deployed standalone and referenced by PoolProxy
*/
abstract contract PoolSwap is PoolInternal {
using SafeERC20 for IERC20;
using ABDKMath64x64 for int128;
using PoolStorage for PoolStorage.Layout;
address internal immutable UNISWAP_V2_FACTORY;
address internal immutable SUSHISWAP_FACTORY;
constructor(
address ivolOracle,
address weth,
address premiaMining,
address feeReceiver,
address feeDiscountAddress,
int128 fee64x64,
address uniswapV2Factory,
address sushiswapFactory
)
PoolInternal(
ivolOracle,
weth,
premiaMining,
feeReceiver,
feeDiscountAddress,
fee64x64
)
{
UNISWAP_V2_FACTORY = uniswapV2Factory;
SUSHISWAP_FACTORY = sushiswapFactory;
}
// calculates the CREATE2 address for a pair without making any external calls
function _pairFor(
address factory,
address tokenA,
address tokenB,
bool isSushi
) internal pure returns (address pair) {
(address token0, address token1) = _sortTokens(tokenA, tokenB);
pair = address(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
isSushi
? hex"e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303"
: hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash
)
)
)
)
);
}
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function _sortTokens(address tokenA, address tokenB)
internal
pure
returns (address token0, address token1)
{
require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB
? (tokenA, tokenB)
: (tokenB, tokenA);
require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS");
}
// performs chained getAmountIn calculations on any number of pairs
function _getAmountsIn(
address factory,
uint256 amountOut,
address[] memory path,
bool isSushi
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "UniswapV2Library: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint256 i = path.length - 1; i > 0; i--) {
(uint256 reserveIn, uint256 reserveOut) = _getReserves(
factory,
path[i - 1],
path[i],
isSushi
);
amounts[i - 1] = _getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
// fetches and sorts the reserves for a pair
function _getReserves(
address factory,
address tokenA,
address tokenB,
bool isSushi
) internal view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = _sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(
_pairFor(factory, tokenA, tokenB, isSushi)
).getReserves();
(reserveA, reserveB) = tokenA == token0
? (reserve0, reserve1)
: (reserve1, reserve0);
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function _getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT");
require(
reserveIn > 0 && reserveOut > 0,
"UniswapV2Library: INSUFFICIENT_LIQUIDITY"
);
uint256 numerator = reserveIn * amountOut * 1000;
uint256 denominator = (reserveOut - amountOut) * 997;
amountIn = (numerator / denominator) + 1;
}
// requires the initial amount to have already been sent to the first pair
function _swap(
uint256[] memory amounts,
address[] memory path,
address _to,
bool isSushi
) internal {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = _sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOut)
: (amountOut, uint256(0));
address to = i < path.length - 2
? _pairFor(
isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY,
output,
path[i + 2],
isSushi
)
: _to;
IUniswapV2Pair(
_pairFor(
isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY,
input,
output,
isSushi
)
).swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function _swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
bool isSushi
) internal returns (uint256[] memory amounts) {
amounts = _getAmountsIn(
isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY,
amountOut,
path,
isSushi
);
require(
amounts[0] <= amountInMax,
"UniswapV2Router: EXCESSIVE_INPUT_AMOUNT"
);
IERC20(path[0]).safeTransferFrom(
msg.sender,
_pairFor(
isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY,
path[0],
path[1],
isSushi
),
amounts[0]
);
_swap(amounts, path, msg.sender, isSushi);
}
function _swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
bool isSushi
) internal returns (uint256[] memory amounts) {
require(path[0] == WETH_ADDRESS, "UniswapV2Router: INVALID_PATH");
amounts = _getAmountsIn(
isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY,
amountOut,
path,
isSushi
);
require(
amounts[0] <= msg.value,
"UniswapV2Router: EXCESSIVE_INPUT_AMOUNT"
);
IWETH(WETH_ADDRESS).deposit{value: amounts[0]}();
assert(
IWETH(WETH_ADDRESS).transfer(
_pairFor(
isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY,
path[0],
path[1],
isSushi
),
amounts[0]
)
);
_swap(amounts, path, msg.sender, isSushi);
// refund dust eth, if any
if (msg.value > amounts[0]) {
(bool success, ) = payable(msg.sender).call{
value: msg.value - amounts[0]
}(new bytes(0));
require(
success,
"TransferHelper::safeTransferETH: ETH transfer failed"
);
}
}
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {AggregatorInterface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorInterface.sol";
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import {EnumerableSet, ERC1155EnumerableStorage} from "@solidstate/contracts/token/ERC1155/enumerable/ERC1155EnumerableStorage.sol";
import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol";
import {ABDKMath64x64Token} from "../libraries/ABDKMath64x64Token.sol";
import {OptionMath} from "../libraries/OptionMath.sol";
library PoolStorage {
using ABDKMath64x64 for int128;
using PoolStorage for PoolStorage.Layout;
enum TokenType {
UNDERLYING_FREE_LIQ,
BASE_FREE_LIQ,
UNDERLYING_RESERVED_LIQ,
BASE_RESERVED_LIQ,
LONG_CALL,
SHORT_CALL,
LONG_PUT,
SHORT_PUT
}
struct PoolSettings {
address underlying;
address base;
address underlyingOracle;
address baseOracle;
}
struct QuoteArgsInternal {
address feePayer; // address of the fee payer
uint64 maturity; // timestamp of option maturity
int128 strike64x64; // 64x64 fixed point representation of strike price
int128 spot64x64; // 64x64 fixed point representation of spot price
uint256 contractSize; // size of option contract
bool isCall; // true for call, false for put
}
struct QuoteResultInternal {
int128 baseCost64x64; // 64x64 fixed point representation of option cost denominated in underlying currency (without fee)
int128 feeCost64x64; // 64x64 fixed point representation of option fee cost denominated in underlying currency for call, or base currency for put
int128 cLevel64x64; // 64x64 fixed point representation of C-Level of Pool after purchase
int128 slippageCoefficient64x64; // 64x64 fixed point representation of slippage coefficient for given order size
}
struct BatchData {
uint256 eta;
uint256 totalPendingDeposits;
}
bytes32 internal constant STORAGE_SLOT =
keccak256("premia.contracts.storage.Pool");
uint256 private constant C_DECAY_BUFFER = 12 hours;
uint256 private constant C_DECAY_INTERVAL = 4 hours;
struct Layout {
// ERC20 token addresses
address base;
address underlying;
// AggregatorV3Interface oracle addresses
address baseOracle;
address underlyingOracle;
// token metadata
uint8 underlyingDecimals;
uint8 baseDecimals;
// minimum amounts
uint256 baseMinimum;
uint256 underlyingMinimum;
// deposit caps
uint256 basePoolCap;
uint256 underlyingPoolCap;
// market state
int128 _deprecated_steepness64x64;
int128 cLevelBase64x64;
int128 cLevelUnderlying64x64;
uint256 cLevelBaseUpdatedAt;
uint256 cLevelUnderlyingUpdatedAt;
uint256 updatedAt;
// User -> isCall -> depositedAt
mapping(address => mapping(bool => uint256)) depositedAt;
mapping(address => mapping(bool => uint256)) divestmentTimestamps;
// doubly linked list of free liquidity intervals
// isCall -> User -> User
mapping(bool => mapping(address => address)) liquidityQueueAscending;
mapping(bool => mapping(address => address)) liquidityQueueDescending;
// minimum resolution price bucket => price
mapping(uint256 => int128) bucketPrices64x64;
// sequence id (minimum resolution price bucket / 256) => price update sequence
mapping(uint256 => uint256) priceUpdateSequences;
// isCall -> batch data
mapping(bool => BatchData) nextDeposits;
// user -> batch timestamp -> isCall -> pending amount
mapping(address => mapping(uint256 => mapping(bool => uint256))) pendingDeposits;
EnumerableSet.UintSet tokenIds;
// user -> isCallPool -> total value locked of user (Used for liquidity mining)
mapping(address => mapping(bool => uint256)) userTVL;
// isCallPool -> total value locked
mapping(bool => uint256) totalTVL;
// steepness values
int128 steepnessBase64x64;
int128 steepnessUnderlying64x64;
}
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
/**
* @notice calculate ERC1155 token id for given option parameters
* @param tokenType TokenType enum
* @param maturity timestamp of option maturity
* @param strike64x64 64x64 fixed point representation of strike price
* @return tokenId token id
*/
function formatTokenId(
TokenType tokenType,
uint64 maturity,
int128 strike64x64
) internal pure returns (uint256 tokenId) {
tokenId =
(uint256(tokenType) << 248) +
(uint256(maturity) << 128) +
uint256(int256(strike64x64));
}
/**
* @notice derive option maturity and strike price from ERC1155 token id
* @param tokenId token id
* @return tokenType TokenType enum
* @return maturity timestamp of option maturity
* @return strike64x64 option strike price
*/
function parseTokenId(uint256 tokenId)
internal
pure
returns (
TokenType tokenType,
uint64 maturity,
int128 strike64x64
)
{
assembly {
tokenType := shr(248, tokenId)
maturity := shr(128, tokenId)
strike64x64 := tokenId
}
}
function getTokenDecimals(Layout storage l, bool isCall)
internal
view
returns (uint8 decimals)
{
decimals = isCall ? l.underlyingDecimals : l.baseDecimals;
}
/**
* @notice get the total supply of free liquidity tokens, minus pending deposits
* @param l storage layout struct
* @param isCall whether query is for call or put pool
* @return 64x64 fixed point representation of total free liquidity
*/
function totalFreeLiquiditySupply64x64(Layout storage l, bool isCall)
internal
view
returns (int128)
{
uint256 tokenId = formatTokenId(
isCall ? TokenType.UNDERLYING_FREE_LIQ : TokenType.BASE_FREE_LIQ,
0,
0
);
return
ABDKMath64x64Token.fromDecimals(
ERC1155EnumerableStorage.layout().totalSupply[tokenId] -
l.nextDeposits[isCall].totalPendingDeposits,
l.getTokenDecimals(isCall)
);
}
function getReinvestmentStatus(
Layout storage l,
address account,
bool isCallPool
) internal view returns (bool) {
uint256 timestamp = l.divestmentTimestamps[account][isCallPool];
return timestamp == 0 || timestamp > block.timestamp;
}
function addUnderwriter(
Layout storage l,
address account,
bool isCallPool
) internal {
require(account != address(0));
mapping(address => address) storage asc = l.liquidityQueueAscending[
isCallPool
];
mapping(address => address) storage desc = l.liquidityQueueDescending[
isCallPool
];
if (_isInQueue(account, asc, desc)) return;
address last = desc[address(0)];
asc[last] = account;
desc[account] = last;
desc[address(0)] = account;
}
function removeUnderwriter(
Layout storage l,
address account,
bool isCallPool
) internal {
require(account != address(0));
mapping(address => address) storage asc = l.liquidityQueueAscending[
isCallPool
];
mapping(address => address) storage desc = l.liquidityQueueDescending[
isCallPool
];
if (!_isInQueue(account, asc, desc)) return;
address prev = desc[account];
address next = asc[account];
asc[prev] = next;
desc[next] = prev;
delete asc[account];
delete desc[account];
}
function isInQueue(
Layout storage l,
address account,
bool isCallPool
) internal view returns (bool) {
mapping(address => address) storage asc = l.liquidityQueueAscending[
isCallPool
];
mapping(address => address) storage desc = l.liquidityQueueDescending[
isCallPool
];
return _isInQueue(account, asc, desc);
}
function _isInQueue(
address account,
mapping(address => address) storage asc,
mapping(address => address) storage desc
) private view returns (bool) {
return asc[account] != address(0) || desc[address(0)] == account;
}
/**
* @notice get current C-Level, without accounting for pending adjustments
* @param l storage layout struct
* @param isCall whether query is for call or put pool
* @return cLevel64x64 64x64 fixed point representation of C-Level
*/
function getRawCLevel64x64(Layout storage l, bool isCall)
internal
view
returns (int128 cLevel64x64)
{
cLevel64x64 = isCall ? l.cLevelUnderlying64x64 : l.cLevelBase64x64;
}
/**
* @notice get current C-Level, accounting for unrealized decay
* @param l storage layout struct
* @param isCall whether query is for call or put pool
* @return cLevel64x64 64x64 fixed point representation of C-Level
*/
function getDecayAdjustedCLevel64x64(Layout storage l, bool isCall)
internal
view
returns (int128 cLevel64x64)
{
// get raw C-Level from storage
cLevel64x64 = l.getRawCLevel64x64(isCall);
// account for C-Level decay
cLevel64x64 = l.applyCLevelDecayAdjustment(cLevel64x64, isCall);
}
/**
* @notice get updated C-Level and pool liquidity level, accounting for decay and pending deposits
* @param l storage layout struct
* @param isCall whether to update C-Level for call or put pool
* @return cLevel64x64 64x64 fixed point representation of C-Level
* @return liquidity64x64 64x64 fixed point representation of new liquidity amount
*/
function getRealPoolState(Layout storage l, bool isCall)
internal
view
returns (int128 cLevel64x64, int128 liquidity64x64)
{
PoolStorage.BatchData storage batchData = l.nextDeposits[isCall];
int128 oldCLevel64x64 = l.getDecayAdjustedCLevel64x64(isCall);
int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall);
if (
batchData.totalPendingDeposits > 0 &&
batchData.eta != 0 &&
block.timestamp >= batchData.eta
) {
liquidity64x64 = ABDKMath64x64Token
.fromDecimals(
batchData.totalPendingDeposits,
l.getTokenDecimals(isCall)
)
.add(oldLiquidity64x64);
cLevel64x64 = l.applyCLevelLiquidityChangeAdjustment(
oldCLevel64x64,
oldLiquidity64x64,
liquidity64x64,
isCall
);
} else {
cLevel64x64 = oldCLevel64x64;
liquidity64x64 = oldLiquidity64x64;
}
}
/**
* @notice calculate updated C-Level, accounting for unrealized decay
* @param l storage layout struct
* @param oldCLevel64x64 64x64 fixed point representation pool C-Level before accounting for decay
* @param isCall whether query is for call or put pool
* @return cLevel64x64 64x64 fixed point representation of C-Level of Pool after accounting for decay
*/
function applyCLevelDecayAdjustment(
Layout storage l,
int128 oldCLevel64x64,
bool isCall
) internal view returns (int128 cLevel64x64) {
uint256 timeElapsed = block.timestamp -
(isCall ? l.cLevelUnderlyingUpdatedAt : l.cLevelBaseUpdatedAt);
// do not apply C decay if less than 24 hours have elapsed
if (timeElapsed > C_DECAY_BUFFER) {
timeElapsed -= C_DECAY_BUFFER;
} else {
return oldCLevel64x64;
}
int128 timeIntervalsElapsed64x64 = ABDKMath64x64.divu(
timeElapsed,
C_DECAY_INTERVAL
);
uint256 tokenId = formatTokenId(
isCall ? TokenType.UNDERLYING_FREE_LIQ : TokenType.BASE_FREE_LIQ,
0,
0
);
uint256 tvl = l.totalTVL[isCall];
int128 utilization = ABDKMath64x64.divu(
tvl -
(ERC1155EnumerableStorage.layout().totalSupply[tokenId] -
l.nextDeposits[isCall].totalPendingDeposits),
tvl
);
return
OptionMath.calculateCLevelDecay(
OptionMath.CalculateCLevelDecayArgs(
timeIntervalsElapsed64x64,
oldCLevel64x64,
utilization,
0xb333333333333333, // 0.7
0xe666666666666666, // 0.9
0x10000000000000000, // 1.0
0x10000000000000000, // 1.0
0xe666666666666666, // 0.9
0x56fc2a2c515da32ea // 2e
)
);
}
/**
* @notice calculate updated C-Level, accounting for change in liquidity
* @param l storage layout struct
* @param oldCLevel64x64 64x64 fixed point representation pool C-Level before accounting for liquidity change
* @param oldLiquidity64x64 64x64 fixed point representation of previous liquidity
* @param newLiquidity64x64 64x64 fixed point representation of current liquidity
* @param isCallPool whether to update C-Level for call or put pool
* @return cLevel64x64 64x64 fixed point representation of C-Level
*/
function applyCLevelLiquidityChangeAdjustment(
Layout storage l,
int128 oldCLevel64x64,
int128 oldLiquidity64x64,
int128 newLiquidity64x64,
bool isCallPool
) internal view returns (int128 cLevel64x64) {
int128 steepness64x64 = isCallPool
? l.steepnessUnderlying64x64
: l.steepnessBase64x64;
// fallback to deprecated storage value if side-specific value is not set
if (steepness64x64 == 0) steepness64x64 = l._deprecated_steepness64x64;
cLevel64x64 = OptionMath.calculateCLevel(
oldCLevel64x64,
oldLiquidity64x64,
newLiquidity64x64,
steepness64x64
);
if (cLevel64x64 < 0xb333333333333333) {
cLevel64x64 = int128(0xb333333333333333); // 64x64 fixed point representation of 0.7
}
}
/**
* @notice set C-Level to arbitrary pre-calculated value
* @param cLevel64x64 new C-Level of pool
* @param isCallPool whether to update C-Level for call or put pool
*/
function setCLevel(
Layout storage l,
int128 cLevel64x64,
bool isCallPool
) internal {
if (isCallPool) {
l.cLevelUnderlying64x64 = cLevel64x64;
l.cLevelUnderlyingUpdatedAt = block.timestamp;
} else {
l.cLevelBase64x64 = cLevel64x64;
l.cLevelBaseUpdatedAt = block.timestamp;
}
}
function setOracles(
Layout storage l,
address baseOracle,
address underlyingOracle
) internal {
require(
AggregatorV3Interface(baseOracle).decimals() ==
AggregatorV3Interface(underlyingOracle).decimals(),
"Pool: oracle decimals must match"
);
l.baseOracle = baseOracle;
l.underlyingOracle = underlyingOracle;
}
function fetchPriceUpdate(Layout storage l)
internal
view
returns (int128 price64x64)
{
int256 priceUnderlying = AggregatorInterface(l.underlyingOracle)
.latestAnswer();
int256 priceBase = AggregatorInterface(l.baseOracle).latestAnswer();
return ABDKMath64x64.divi(priceUnderlying, priceBase);
}
/**
* @notice set price update for hourly bucket corresponding to given timestamp
* @param l storage layout struct
* @param timestamp timestamp to update
* @param price64x64 64x64 fixed point representation of price
*/
function setPriceUpdate(
Layout storage l,
uint256 timestamp,
int128 price64x64
) internal {
uint256 bucket = timestamp / (1 hours);
l.bucketPrices64x64[bucket] = price64x64;
l.priceUpdateSequences[bucket >> 8] += 1 << (255 - (bucket & 255));
}
/**
* @notice get price update for hourly bucket corresponding to given timestamp
* @param l storage layout struct
* @param timestamp timestamp to query
* @return 64x64 fixed point representation of price
*/
function getPriceUpdate(Layout storage l, uint256 timestamp)
internal
view
returns (int128)
{
return l.bucketPrices64x64[timestamp / (1 hours)];
}
/**
* @notice get first price update available following given timestamp
* @param l storage layout struct
* @param timestamp timestamp to query
* @return 64x64 fixed point representation of price
*/
function getPriceUpdateAfter(Layout storage l, uint256 timestamp)
internal
view
returns (int128)
{
// price updates are grouped into hourly buckets
uint256 bucket = timestamp / (1 hours);
// divide by 256 to get the index of the relevant price update sequence
uint256 sequenceId = bucket >> 8;
// get position within sequence relevant to current price update
uint256 offset = bucket & 255;
// shift to skip buckets from earlier in sequence
uint256 sequence = (l.priceUpdateSequences[sequenceId] << offset) >>
offset;
// iterate through future sequences until a price update is found
// sequence corresponding to current timestamp used as upper bound
uint256 currentPriceUpdateSequenceId = block.timestamp / (256 hours);
while (sequence == 0 && sequenceId <= currentPriceUpdateSequenceId) {
sequence = l.priceUpdateSequences[++sequenceId];
}
// if no price update is found (sequence == 0) function will return 0
// this should never occur, as each relevant external function triggers a price update
// the most significant bit of the sequence corresponds to the offset of the relevant bucket
uint256 msb;
for (uint256 i = 128; i > 0; i >>= 1) {
if (sequence >> i > 0) {
msb += i;
sequence >>= i;
}
}
return l.bucketPrices64x64[((sequenceId + 1) << 8) - msb - 1];
}
function fromBaseToUnderlyingDecimals(Layout storage l, uint256 value)
internal
view
returns (uint256)
{
int128 valueFixed64x64 = ABDKMath64x64Token.fromDecimals(
value,
l.baseDecimals
);
return
ABDKMath64x64Token.toDecimals(
valueFixed64x64,
l.underlyingDecimals
);
}
function fromUnderlyingToBaseDecimals(Layout storage l, uint256 value)
internal
view
returns (uint256)
{
int128 valueFixed64x64 = ABDKMath64x64Token.fromDecimals(
value,
l.underlyingDecimals
);
return ABDKMath64x64Token.toDecimals(valueFixed64x64, l.baseDecimals);
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.0;
import {PremiaMiningStorage} from "./PremiaMiningStorage.sol";
interface IPremiaMining {
function addPremiaRewards(uint256 _amount) external;
function premiaRewardsAvailable() external view returns (uint256);
function getTotalAllocationPoints() external view returns (uint256);
function getPoolInfo(address pool, bool isCallPool)
external
view
returns (PremiaMiningStorage.PoolInfo memory);
function getPremiaPerYear() external view returns (uint256);
function addPool(address _pool, uint256 _allocPoints) external;
function setPoolAllocPoints(
address[] memory _pools,
uint256[] memory _allocPoints
) external;
function pendingPremia(
address _pool,
bool _isCallPool,
address _user
) external view returns (uint256);
function updatePool(
address _pool,
bool _isCallPool,
uint256 _totalTVL
) external;
function allocatePending(
address _user,
address _pool,
bool _isCallPool,
uint256 _userTVLOld,
uint256 _userTVLNew,
uint256 _totalTVL
) external;
function claim(
address _user,
address _pool,
bool _isCallPool,
uint256 _userTVLOld,
uint256 _userTVLNew,
uint256 _totalTVL
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC20 } from '../token/ERC20/IERC20.sol';
import { IERC20Metadata } from '../token/ERC20/metadata/IERC20Metadata.sol';
/**
* @title WETH (Wrapped ETH) interface
*/
interface IWETH is IERC20, IERC20Metadata {
/**
* @notice convert ETH to WETH
*/
function deposit() external payable;
/**
* @notice convert WETH to ETH
* @dev if caller is a contract, it should have a fallback or receive function
* @param amount quantity of WETH to convert, denominated in wei
*/
function withdraw(uint256 amount) external;
}
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC20 } from '../token/ERC20/IERC20.sol';
import { AddressUtils } from './AddressUtils.sol';
/**
* @title Safe ERC20 interaction library
* @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license)
*/
library SafeERC20 {
using AddressUtils for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
/**
* @dev safeApprove (like approve) should only be called when setting an initial allowance or when resetting it to zero; otherwise prefer safeIncreaseAllowance and safeDecreaseAllowance
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
'SafeERC20: approve from non-zero to non-zero allowance'
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, value)
);
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(
oldAllowance >= value,
'SafeERC20: decreased allowance below zero'
);
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
}
/**
* @notice send transaction data and check validity of return value, if present
* @param token ERC20 token interface
* @param data transaction data
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(
data,
'SafeERC20: low-level call failed'
);
if (returndata.length > 0) {
require(
abi.decode(returndata, (bool)),
'SafeERC20: ERC20 operation did not succeed'
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC20Internal } from './IERC20Internal.sol';
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 is IERC20Internal {
/**
* @notice query the total minted token supply
* @return token supply
*/
function totalSupply() external view returns (uint256);
/**
* @notice query the token balance of given account
* @param account address to query
* @return token balance
*/
function balanceOf(address account) external view returns (uint256);
/**
* @notice query the allowance granted from given holder to given spender
* @param holder approver of allowance
* @param spender recipient of allowance
* @return token allowance
*/
function allowance(address holder, address spender)
external
view
returns (uint256);
/**
* @notice grant approval to spender to spend tokens
* @dev prefer ERC20Extended functions to avoid transaction-ordering vulnerability (see https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729)
* @param spender recipient of allowance
* @param amount quantity of tokens approved for spending
* @return success status (always true; otherwise function should revert)
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @notice transfer tokens to given recipient
* @param recipient beneficiary of token transfer
* @param amount quantity of tokens to transfer
* @return success status (always true; otherwise function should revert)
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @notice transfer tokens to given recipient on behalf of given holder
* @param holder holder of tokens prior to transfer
* @param recipient beneficiary of token transfer
* @param amount quantity of tokens to transfer
* @return success status (always true; otherwise function should revert)
*/
function transferFrom(
address holder,
address recipient,
uint256 amount
) external returns (bool);
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {IERC173} from "@solidstate/contracts/access/IERC173.sol";
import {OwnableStorage} from "@solidstate/contracts/access/OwnableStorage.sol";
import {IERC20} from "@solidstate/contracts/token/ERC20/IERC20.sol";
import {ERC1155EnumerableInternal, ERC1155EnumerableStorage, EnumerableSet} from "@solidstate/contracts/token/ERC1155/enumerable/ERC1155Enumerable.sol";
import {IWETH} from "@solidstate/contracts/utils/IWETH.sol";
import {PoolStorage} from "./PoolStorage.sol";
import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol";
import {ABDKMath64x64Token} from "../libraries/ABDKMath64x64Token.sol";
import {OptionMath} from "../libraries/OptionMath.sol";
import {IFeeDiscount} from "../staking/IFeeDiscount.sol";
import {IPoolEvents} from "./IPoolEvents.sol";
import {IPremiaMining} from "../mining/IPremiaMining.sol";
import {IVolatilitySurfaceOracle} from "../oracle/IVolatilitySurfaceOracle.sol";
/**
* @title Premia option pool
* @dev deployed standalone and referenced by PoolProxy
*/
contract PoolInternal is IPoolEvents, ERC1155EnumerableInternal {
using ABDKMath64x64 for int128;
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using PoolStorage for PoolStorage.Layout;
address internal immutable WETH_ADDRESS;
address internal immutable PREMIA_MINING_ADDRESS;
address internal immutable FEE_RECEIVER_ADDRESS;
address internal immutable FEE_DISCOUNT_ADDRESS;
address internal immutable IVOL_ORACLE_ADDRESS;
int128 internal immutable FEE_64x64;
uint256 internal immutable UNDERLYING_FREE_LIQ_TOKEN_ID;
uint256 internal immutable BASE_FREE_LIQ_TOKEN_ID;
uint256 internal immutable UNDERLYING_RESERVED_LIQ_TOKEN_ID;
uint256 internal immutable BASE_RESERVED_LIQ_TOKEN_ID;
uint256 internal constant INVERSE_BASIS_POINT = 1e4;
uint256 internal constant BATCHING_PERIOD = 260;
// Minimum APY for capital locked up to underwrite options.
// The quote will return a minimum price corresponding to this APY
int128 internal constant MIN_APY_64x64 = 0x4ccccccccccccccd; // 0.3
constructor(
address ivolOracle,
address weth,
address premiaMining,
address feeReceiver,
address feeDiscountAddress,
int128 fee64x64
) {
IVOL_ORACLE_ADDRESS = ivolOracle;
WETH_ADDRESS = weth;
PREMIA_MINING_ADDRESS = premiaMining;
FEE_RECEIVER_ADDRESS = feeReceiver;
// PremiaFeeDiscount contract address
FEE_DISCOUNT_ADDRESS = feeDiscountAddress;
FEE_64x64 = fee64x64;
UNDERLYING_FREE_LIQ_TOKEN_ID = PoolStorage.formatTokenId(
PoolStorage.TokenType.UNDERLYING_FREE_LIQ,
0,
0
);
BASE_FREE_LIQ_TOKEN_ID = PoolStorage.formatTokenId(
PoolStorage.TokenType.BASE_FREE_LIQ,
0,
0
);
UNDERLYING_RESERVED_LIQ_TOKEN_ID = PoolStorage.formatTokenId(
PoolStorage.TokenType.UNDERLYING_RESERVED_LIQ,
0,
0
);
BASE_RESERVED_LIQ_TOKEN_ID = PoolStorage.formatTokenId(
PoolStorage.TokenType.BASE_RESERVED_LIQ,
0,
0
);
}
modifier onlyProtocolOwner() {
require(
msg.sender == IERC173(OwnableStorage.layout().owner).owner(),
"Not protocol owner"
);
_;
}
function _getFeeDiscount(address feePayer)
internal
view
returns (uint256 discount)
{
if (FEE_DISCOUNT_ADDRESS != address(0)) {
discount = IFeeDiscount(FEE_DISCOUNT_ADDRESS).getDiscount(feePayer);
}
}
function _getFeeWithDiscount(address feePayer, uint256 fee)
internal
view
returns (uint256)
{
uint256 discount = _getFeeDiscount(feePayer);
return fee - ((fee * discount) / INVERSE_BASIS_POINT);
}
function _withdrawFees(bool isCall) internal returns (uint256 amount) {
uint256 tokenId = _getReservedLiquidityTokenId(isCall);
amount = _balanceOf(FEE_RECEIVER_ADDRESS, tokenId);
if (amount > 0) {
_burn(FEE_RECEIVER_ADDRESS, tokenId, amount);
emit FeeWithdrawal(isCall, amount);
}
}
/**
* @notice calculate price of option contract
* @param args structured quote arguments
* @return result quote result
*/
function _quote(PoolStorage.QuoteArgsInternal memory args)
internal
view
returns (PoolStorage.QuoteResultInternal memory result)
{
require(
args.strike64x64 > 0 && args.spot64x64 > 0 && args.maturity > 0,
"invalid args"
);
PoolStorage.Layout storage l = PoolStorage.layout();
int128 contractSize64x64 = ABDKMath64x64Token.fromDecimals(
args.contractSize,
l.underlyingDecimals
);
(int128 adjustedCLevel64x64, int128 oldLiquidity64x64) = l
.getRealPoolState(args.isCall);
require(oldLiquidity64x64 > 0, "no liq");
int128 timeToMaturity64x64 = ABDKMath64x64.divu(
args.maturity - block.timestamp,
365 days
);
int128 annualizedVolatility64x64 = IVolatilitySurfaceOracle(
IVOL_ORACLE_ADDRESS
).getAnnualizedVolatility64x64(
l.base,
l.underlying,
args.spot64x64,
args.strike64x64,
timeToMaturity64x64,
args.isCall
);
require(annualizedVolatility64x64 > 0, "vol = 0");
int128 collateral64x64 = args.isCall
? contractSize64x64
: contractSize64x64.mul(args.strike64x64);
(
int128 price64x64,
int128 cLevel64x64,
int128 slippageCoefficient64x64
) = OptionMath.quotePrice(
OptionMath.QuoteArgs(
annualizedVolatility64x64.mul(annualizedVolatility64x64),
args.strike64x64,
args.spot64x64,
timeToMaturity64x64,
adjustedCLevel64x64,
oldLiquidity64x64,
oldLiquidity64x64.sub(collateral64x64),
0x10000000000000000, // 64x64 fixed point representation of 1
MIN_APY_64x64,
args.isCall
)
);
result.baseCost64x64 = args.isCall
? price64x64.mul(contractSize64x64).div(args.spot64x64)
: price64x64.mul(contractSize64x64);
result.feeCost64x64 = result.baseCost64x64.mul(FEE_64x64);
result.cLevel64x64 = cLevel64x64;
result.slippageCoefficient64x64 = slippageCoefficient64x64;
int128 discount = ABDKMath64x64.divu(
_getFeeDiscount(args.feePayer),
INVERSE_BASIS_POINT
);
result.feeCost64x64 -= result.feeCost64x64.mul(discount);
}
/**
* @notice burn corresponding long and short option tokens
* @param account holder of tokens to annihilate
* @param maturity timestamp of option maturity
* @param strike64x64 64x64 fixed point representation of strike price
* @param isCall true for call, false for put
* @param contractSize quantity of option contract tokens to annihilate
*/
function _annihilate(
address account,
uint64 maturity,
int128 strike64x64,
bool isCall,
uint256 contractSize
) internal {
uint256 longTokenId = PoolStorage.formatTokenId(
_getTokenType(isCall, true),
maturity,
strike64x64
);
uint256 shortTokenId = PoolStorage.formatTokenId(
_getTokenType(isCall, false),
maturity,
strike64x64
);
_burn(account, longTokenId, contractSize);
_burn(account, shortTokenId, contractSize);
emit Annihilate(shortTokenId, contractSize);
}
/**
* @notice purchase option
* @param l storage layout struct
* @param account recipient of purchased option
* @param maturity timestamp of option maturity
* @param strike64x64 64x64 fixed point representation of strike price
* @param isCall true for call, false for put
* @param contractSize size of option contract
* @param newPrice64x64 64x64 fixed point representation of current spot price
* @return baseCost quantity of tokens required to purchase long position
* @return feeCost quantity of tokens required to pay fees
*/
function _purchase(
PoolStorage.Layout storage l,
address account,
uint64 maturity,
int128 strike64x64,
bool isCall,
uint256 contractSize,
int128 newPrice64x64
) internal returns (uint256 baseCost, uint256 feeCost) {
require(maturity > block.timestamp, "expired");
require(contractSize >= l.underlyingMinimum, "too small");
{
uint256 size = isCall
? contractSize
: l.fromUnderlyingToBaseDecimals(
strike64x64.mulu(contractSize)
);
require(
size <=
ERC1155EnumerableStorage.layout().totalSupply[
_getFreeLiquidityTokenId(isCall)
] -
l.nextDeposits[isCall].totalPendingDeposits,
"insuf liq"
);
}
PoolStorage.QuoteResultInternal memory quote = _quote(
PoolStorage.QuoteArgsInternal(
account,
maturity,
strike64x64,
newPrice64x64,
contractSize,
isCall
)
);
baseCost = ABDKMath64x64Token.toDecimals(
quote.baseCost64x64,
l.getTokenDecimals(isCall)
);
feeCost = ABDKMath64x64Token.toDecimals(
quote.feeCost64x64,
l.getTokenDecimals(isCall)
);
uint256 longTokenId = PoolStorage.formatTokenId(
_getTokenType(isCall, true),
maturity,
strike64x64
);
uint256 shortTokenId = PoolStorage.formatTokenId(
_getTokenType(isCall, false),
maturity,
strike64x64
);
// mint long option token for buyer
_mint(account, longTokenId, contractSize);
int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall);
// burn free liquidity tokens from other underwriters
_mintShortTokenLoop(
l,
account,
contractSize,
baseCost,
shortTokenId,
isCall
);
int128 newLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall);
_setCLevel(l, oldLiquidity64x64, newLiquidity64x64, isCall);
// mint reserved liquidity tokens for fee receiver
_mint(
FEE_RECEIVER_ADDRESS,
_getReservedLiquidityTokenId(isCall),
feeCost
);
emit Purchase(
account,
longTokenId,
contractSize,
baseCost,
feeCost,
newPrice64x64
);
}
/**
* @notice reassign short position to new underwriter
* @param l storage layout struct
* @param account holder of positions to be reassigned
* @param maturity timestamp of option maturity
* @param strike64x64 64x64 fixed point representation of strike price
* @param isCall true for call, false for put
* @param contractSize quantity of option contract tokens to reassign
* @param newPrice64x64 64x64 fixed point representation of current spot price
* @return baseCost quantity of tokens required to reassign short position
* @return feeCost quantity of tokens required to pay fees
* @return amountOut quantity of liquidity freed
*/
function _reassign(
PoolStorage.Layout storage l,
address account,
uint64 maturity,
int128 strike64x64,
bool isCall,
uint256 contractSize,
int128 newPrice64x64
)
internal
returns (
uint256 baseCost,
uint256 feeCost,
uint256 amountOut
)
{
(baseCost, feeCost) = _purchase(
l,
account,
maturity,
strike64x64,
isCall,
contractSize,
newPrice64x64
);
_annihilate(account, maturity, strike64x64, isCall, contractSize);
uint256 annihilateAmount = isCall
? contractSize
: l.fromUnderlyingToBaseDecimals(strike64x64.mulu(contractSize));
amountOut = annihilateAmount - baseCost - feeCost;
}
/**
* @notice exercise option on behalf of holder
* @dev used for processing of expired options if passed holder is zero address
* @param holder owner of long option tokens to exercise
* @param longTokenId long option token id
* @param contractSize quantity of tokens to exercise
*/
function _exercise(
address holder,
uint256 longTokenId,
uint256 contractSize
) internal {
uint64 maturity;
int128 strike64x64;
bool isCall;
bool onlyExpired = holder == address(0);
{
PoolStorage.TokenType tokenType;
(tokenType, maturity, strike64x64) = PoolStorage.parseTokenId(
longTokenId
);
require(
tokenType == PoolStorage.TokenType.LONG_CALL ||
tokenType == PoolStorage.TokenType.LONG_PUT,
"invalid type"
);
require(!onlyExpired || maturity < block.timestamp, "not expired");
isCall = tokenType == PoolStorage.TokenType.LONG_CALL;
}
PoolStorage.Layout storage l = PoolStorage.layout();
int128 spot64x64 = _update(l);
if (maturity < block.timestamp) {
spot64x64 = l.getPriceUpdateAfter(maturity);
}
require(
onlyExpired ||
(
isCall
? (spot64x64 > strike64x64)
: (spot64x64 < strike64x64)
),
"not ITM"
);
uint256 exerciseValue;
// option has a non-zero exercise value
if (isCall) {
if (spot64x64 > strike64x64) {
exerciseValue = spot64x64.sub(strike64x64).div(spot64x64).mulu(
contractSize
);
}
} else {
if (spot64x64 < strike64x64) {
exerciseValue = l.fromUnderlyingToBaseDecimals(
strike64x64.sub(spot64x64).mulu(contractSize)
);
}
}
uint256 totalFee;
if (onlyExpired) {
totalFee += _burnLongTokenLoop(
contractSize,
exerciseValue,
longTokenId,
isCall
);
} else {
// burn long option tokens from sender
_burn(holder, longTokenId, contractSize);
uint256 fee;
if (exerciseValue > 0) {
fee = _getFeeWithDiscount(
holder,
FEE_64x64.mulu(exerciseValue)
);
totalFee += fee;
_pushTo(holder, _getPoolToken(isCall), exerciseValue - fee);
}
emit Exercise(
holder,
longTokenId,
contractSize,
exerciseValue,
fee
);
}
totalFee += _burnShortTokenLoop(
contractSize,
exerciseValue,
PoolStorage.formatTokenId(
_getTokenType(isCall, false),
maturity,
strike64x64
),
isCall
);
_mint(
FEE_RECEIVER_ADDRESS,
_getReservedLiquidityTokenId(isCall),
totalFee
);
}
function _mintShortTokenLoop(
PoolStorage.Layout storage l,
address buyer,
uint256 contractSize,
uint256 premium,
uint256 shortTokenId,
bool isCall
) internal {
uint256 freeLiqTokenId = _getFreeLiquidityTokenId(isCall);
(, , int128 strike64x64) = PoolStorage.parseTokenId(shortTokenId);
uint256 toPay = isCall
? contractSize
: l.fromUnderlyingToBaseDecimals(strike64x64.mulu(contractSize));
while (toPay > 0) {
address underwriter = l.liquidityQueueAscending[isCall][address(0)];
uint256 balance = _balanceOf(underwriter, freeLiqTokenId);
// If dust left, we remove underwriter and skip to next
if (balance < _getMinimumAmount(l, isCall)) {
l.removeUnderwriter(underwriter, isCall);
continue;
}
if (!l.getReinvestmentStatus(underwriter, isCall)) {
_burn(underwriter, freeLiqTokenId, balance);
_mint(
underwriter,
_getReservedLiquidityTokenId(isCall),
balance
);
_subUserTVL(l, underwriter, isCall, balance);
continue;
}
// amount of liquidity provided by underwriter, accounting for reinvested premium
uint256 intervalContractSize = ((balance -
l.pendingDeposits[underwriter][l.nextDeposits[isCall].eta][
isCall
]) * (toPay + premium)) / toPay;
if (intervalContractSize == 0) continue;
if (intervalContractSize > toPay) intervalContractSize = toPay;
// amount of premium paid to underwriter
uint256 intervalPremium = (premium * intervalContractSize) / toPay;
premium -= intervalPremium;
toPay -= intervalContractSize;
_addUserTVL(l, underwriter, isCall, intervalPremium);
// burn free liquidity tokens from underwriter
_burn(
underwriter,
freeLiqTokenId,
intervalContractSize - intervalPremium
);
if (isCall == false) {
// For PUT, conversion to contract amount is done here (Prior to this line, it is token amount)
intervalContractSize = l.fromBaseToUnderlyingDecimals(
strike64x64.inv().mulu(intervalContractSize)
);
}
// mint short option tokens for underwriter
// toPay == 0 ? contractSize : intervalContractSize : To prevent minting less than amount,
// because of rounding (Can happen for put, because of fixed point precision)
_mint(
underwriter,
shortTokenId,
toPay == 0 ? contractSize : intervalContractSize
);
emit Underwrite(
underwriter,
buyer,
shortTokenId,
toPay == 0 ? contractSize : intervalContractSize,
intervalPremium,
false
);
contractSize -= intervalContractSize;
}
}
function _burnLongTokenLoop(
uint256 contractSize,
uint256 exerciseValue,
uint256 longTokenId,
bool isCall
) internal returns (uint256 totalFee) {
EnumerableSet.AddressSet storage holders = ERC1155EnumerableStorage
.layout()
.accountsByToken[longTokenId];
while (contractSize > 0) {
address longTokenHolder = holders.at(holders.length() - 1);
uint256 intervalContractSize = _balanceOf(
longTokenHolder,
longTokenId
);
if (intervalContractSize > contractSize)
intervalContractSize = contractSize;
uint256 intervalExerciseValue;
uint256 fee;
if (exerciseValue > 0) {
intervalExerciseValue =
(exerciseValue * intervalContractSize) /
contractSize;
fee = _getFeeWithDiscount(
longTokenHolder,
FEE_64x64.mulu(intervalExerciseValue)
);
totalFee += fee;
exerciseValue -= intervalExerciseValue;
_pushTo(
longTokenHolder,
_getPoolToken(isCall),
intervalExerciseValue - fee
);
}
contractSize -= intervalContractSize;
emit Exercise(
longTokenHolder,
longTokenId,
intervalContractSize,
intervalExerciseValue - fee,
fee
);
_burn(longTokenHolder, longTokenId, intervalContractSize);
}
}
function _burnShortTokenLoop(
uint256 contractSize,
uint256 exerciseValue,
uint256 shortTokenId,
bool isCall
) internal returns (uint256 totalFee) {
EnumerableSet.AddressSet storage underwriters = ERC1155EnumerableStorage
.layout()
.accountsByToken[shortTokenId];
(, , int128 strike64x64) = PoolStorage.parseTokenId(shortTokenId);
while (contractSize > 0) {
address underwriter = underwriters.at(underwriters.length() - 1);
// amount of liquidity provided by underwriter
uint256 intervalContractSize = _balanceOf(
underwriter,
shortTokenId
);
if (intervalContractSize > contractSize)
intervalContractSize = contractSize;
// amount of value claimed by buyer
uint256 intervalExerciseValue = (exerciseValue *
intervalContractSize) / contractSize;
exerciseValue -= intervalExerciseValue;
contractSize -= intervalContractSize;
uint256 freeLiq = isCall
? intervalContractSize - intervalExerciseValue
: PoolStorage.layout().fromUnderlyingToBaseDecimals(
strike64x64.mulu(intervalContractSize)
) - intervalExerciseValue;
uint256 fee = _getFeeWithDiscount(
underwriter,
FEE_64x64.mulu(freeLiq)
);
totalFee += fee;
uint256 tvlToSubtract = intervalExerciseValue;
// mint free liquidity tokens for underwriter
if (
PoolStorage.layout().getReinvestmentStatus(underwriter, isCall)
) {
_addToDepositQueue(underwriter, freeLiq - fee, isCall);
tvlToSubtract += fee;
} else {
_mint(
underwriter,
_getReservedLiquidityTokenId(isCall),
freeLiq - fee
);
tvlToSubtract += freeLiq;
}
_subUserTVL(
PoolStorage.layout(),
underwriter,
isCall,
tvlToSubtract
);
// burn short option tokens from underwriter
_burn(underwriter, shortTokenId, intervalContractSize);
emit AssignExercise(
underwriter,
shortTokenId,
freeLiq - fee,
intervalContractSize,
fee
);
}
}
function _addToDepositQueue(
address account,
uint256 amount,
bool isCallPool
) internal {
PoolStorage.Layout storage l = PoolStorage.layout();
_mint(account, _getFreeLiquidityTokenId(isCallPool), amount);
uint256 nextBatch = (block.timestamp / BATCHING_PERIOD) *
BATCHING_PERIOD +
BATCHING_PERIOD;
l.pendingDeposits[account][nextBatch][isCallPool] += amount;
PoolStorage.BatchData storage batchData = l.nextDeposits[isCallPool];
batchData.totalPendingDeposits += amount;
batchData.eta = nextBatch;
}
function _processPendingDeposits(PoolStorage.Layout storage l, bool isCall)
internal
{
PoolStorage.BatchData storage data = l.nextDeposits[isCall];
if (data.eta == 0 || block.timestamp < data.eta) return;
int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall);
_setCLevel(
l,
oldLiquidity64x64,
oldLiquidity64x64.add(
ABDKMath64x64Token.fromDecimals(
data.totalPendingDeposits,
l.getTokenDecimals(isCall)
)
),
isCall
);
delete l.nextDeposits[isCall];
}
function _getFreeLiquidityTokenId(bool isCall)
internal
view
returns (uint256 freeLiqTokenId)
{
freeLiqTokenId = isCall
? UNDERLYING_FREE_LIQ_TOKEN_ID
: BASE_FREE_LIQ_TOKEN_ID;
}
function _getReservedLiquidityTokenId(bool isCall)
internal
view
returns (uint256 reservedLiqTokenId)
{
reservedLiqTokenId = isCall
? UNDERLYING_RESERVED_LIQ_TOKEN_ID
: BASE_RESERVED_LIQ_TOKEN_ID;
}
function _getPoolToken(bool isCall) internal view returns (address token) {
token = isCall
? PoolStorage.layout().underlying
: PoolStorage.layout().base;
}
function _getTokenType(bool isCall, bool isLong)
internal
pure
returns (PoolStorage.TokenType tokenType)
{
if (isCall) {
tokenType = isLong
? PoolStorage.TokenType.LONG_CALL
: PoolStorage.TokenType.SHORT_CALL;
} else {
tokenType = isLong
? PoolStorage.TokenType.LONG_PUT
: PoolStorage.TokenType.SHORT_PUT;
}
}
function _getMinimumAmount(PoolStorage.Layout storage l, bool isCall)
internal
view
returns (uint256 minimumAmount)
{
minimumAmount = isCall ? l.underlyingMinimum : l.baseMinimum;
}
function _getPoolCapAmount(PoolStorage.Layout storage l, bool isCall)
internal
view
returns (uint256 poolCapAmount)
{
poolCapAmount = isCall ? l.underlyingPoolCap : l.basePoolCap;
}
function _setCLevel(
PoolStorage.Layout storage l,
int128 oldLiquidity64x64,
int128 newLiquidity64x64,
bool isCallPool
) internal {
int128 oldCLevel64x64 = l.getDecayAdjustedCLevel64x64(isCallPool);
int128 cLevel64x64 = l.applyCLevelLiquidityChangeAdjustment(
oldCLevel64x64,
oldLiquidity64x64,
newLiquidity64x64,
isCallPool
);
l.setCLevel(cLevel64x64, isCallPool);
emit UpdateCLevel(
isCallPool,
cLevel64x64,
oldLiquidity64x64,
newLiquidity64x64
);
}
/**
* @notice calculate and store updated market state
* @param l storage layout struct
* @return newPrice64x64 64x64 fixed point representation of current spot price
*/
function _update(PoolStorage.Layout storage l)
internal
returns (int128 newPrice64x64)
{
if (l.updatedAt == block.timestamp) {
return (l.getPriceUpdate(block.timestamp));
}
newPrice64x64 = l.fetchPriceUpdate();
if (l.getPriceUpdate(block.timestamp) == 0) {
l.setPriceUpdate(block.timestamp, newPrice64x64);
}
l.updatedAt = block.timestamp;
_processPendingDeposits(l, true);
_processPendingDeposits(l, false);
}
/**
* @notice transfer ERC20 tokens to message sender
* @param token ERC20 token address
* @param amount quantity of token to transfer
*/
function _pushTo(
address to,
address token,
uint256 amount
) internal {
if (amount == 0) return;
require(IERC20(token).transfer(to, amount), "ERC20 transfer failed");
}
/**
* @notice transfer ERC20 tokens from message sender
* @param from address from which tokens are pulled from
* @param token ERC20 token address
* @param amount quantity of token to transfer
* @param skipWethDeposit if false, will not try to deposit weth from attach eth
*/
function _pullFrom(
address from,
address token,
uint256 amount,
bool skipWethDeposit
) internal {
if (!skipWethDeposit) {
if (token == WETH_ADDRESS) {
if (msg.value > 0) {
if (msg.value > amount) {
IWETH(WETH_ADDRESS).deposit{value: amount}();
(bool success, ) = payable(msg.sender).call{
value: msg.value - amount
}("");
require(success, "ETH refund failed");
amount = 0;
} else {
unchecked {
amount -= msg.value;
}
IWETH(WETH_ADDRESS).deposit{value: msg.value}();
}
}
} else {
require(msg.value == 0, "not WETH deposit");
}
}
if (amount > 0) {
require(
IERC20(token).transferFrom(from, address(this), amount),
"ERC20 transfer failed"
);
}
}
function _mint(
address account,
uint256 tokenId,
uint256 amount
) internal {
_mint(account, tokenId, amount, "");
}
function _addUserTVL(
PoolStorage.Layout storage l,
address user,
bool isCallPool,
uint256 amount
) internal {
uint256 userTVL = l.userTVL[user][isCallPool];
uint256 totalTVL = l.totalTVL[isCallPool];
IPremiaMining(PREMIA_MINING_ADDRESS).allocatePending(
user,
address(this),
isCallPool,
userTVL,
userTVL + amount,
totalTVL
);
l.userTVL[user][isCallPool] = userTVL + amount;
l.totalTVL[isCallPool] = totalTVL + amount;
}
function _subUserTVL(
PoolStorage.Layout storage l,
address user,
bool isCallPool,
uint256 amount
) internal {
uint256 userTVL = l.userTVL[user][isCallPool];
uint256 totalTVL = l.totalTVL[isCallPool];
IPremiaMining(PREMIA_MINING_ADDRESS).allocatePending(
user,
address(this),
isCallPool,
userTVL,
userTVL - amount,
totalTVL
);
l.userTVL[user][isCallPool] = userTVL - amount;
l.totalTVL[isCallPool] = totalTVL - amount;
}
/**
* @notice ERC1155 hook: track eligible underwriters
* @param operator transaction sender
* @param from token sender
* @param to token receiver
* @param ids token ids transferred
* @param amounts token quantities transferred
* @param data data payload
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
PoolStorage.Layout storage l = PoolStorage.layout();
for (uint256 i; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
if (amount == 0) continue;
if (from == address(0)) {
l.tokenIds.add(id);
}
if (
to == address(0) &&
ERC1155EnumerableStorage.layout().totalSupply[id] == 0
) {
l.tokenIds.remove(id);
}
// prevent transfer of free and reserved liquidity during waiting period
if (
id == UNDERLYING_FREE_LIQ_TOKEN_ID ||
id == BASE_FREE_LIQ_TOKEN_ID ||
id == UNDERLYING_RESERVED_LIQ_TOKEN_ID ||
id == BASE_RESERVED_LIQ_TOKEN_ID
) {
if (from != address(0) && to != address(0)) {
bool isCallPool = id == UNDERLYING_FREE_LIQ_TOKEN_ID ||
id == UNDERLYING_RESERVED_LIQ_TOKEN_ID;
require(
l.depositedAt[from][isCallPool] + (1 days) <
block.timestamp,
"liq lock 1d"
);
}
}
if (
id == UNDERLYING_FREE_LIQ_TOKEN_ID ||
id == BASE_FREE_LIQ_TOKEN_ID
) {
bool isCallPool = id == UNDERLYING_FREE_LIQ_TOKEN_ID;
uint256 minimum = _getMinimumAmount(l, isCallPool);
if (from != address(0)) {
uint256 balance = _balanceOf(from, id);
if (balance > minimum && balance <= amount + minimum) {
require(
balance -
l.pendingDeposits[from][
l.nextDeposits[isCallPool].eta
][isCallPool] >=
amount,
"Insuf balance"
);
l.removeUnderwriter(from, isCallPool);
}
if (to != address(0)) {
_subUserTVL(l, from, isCallPool, amounts[i]);
_addUserTVL(l, to, isCallPool, amounts[i]);
}
}
if (to != address(0)) {
uint256 balance = _balanceOf(to, id);
if (balance <= minimum && balance + amount > minimum) {
l.addUnderwriter(to, isCallPool);
}
}
}
// Update userTVL on SHORT options transfers
(
PoolStorage.TokenType tokenType,
,
int128 strike64x64
) = PoolStorage.parseTokenId(id);
if (
(from != address(0) && to != address(0)) &&
(tokenType == PoolStorage.TokenType.SHORT_CALL ||
tokenType == PoolStorage.TokenType.SHORT_PUT)
) {
bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL;
uint256 collateral = isCall
? amount
: l.fromUnderlyingToBaseDecimals(strike64x64.mulu(amount));
_subUserTVL(l, from, isCall, collateral);
_addUserTVL(l, to, isCall, collateral);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorInterface {
function latestAnswer()
external
view
returns (
int256
);
function latestTimestamp()
external
view
returns (
uint256
);
function latestRound()
external
view
returns (
uint256
);
function getAnswer(
uint256 roundId
)
external
view
returns (
int256
);
function getTimestamp(
uint256 roundId
)
external
view
returns (
uint256
);
event AnswerUpdated(
int256 indexed current,
uint256 indexed roundId,
uint256 updatedAt
);
event NewRound(
uint256 indexed roundId,
address indexed startedBy,
uint256 startedAt
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorV3Interface {
function decimals()
external
view
returns (
uint8
);
function description()
external
view
returns (
string memory
);
function version()
external
view
returns (
uint256
);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(
uint80 _roundId
)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { EnumerableSet } from '../../../utils/EnumerableSet.sol';
library ERC1155EnumerableStorage {
struct Layout {
mapping(uint256 => uint256) totalSupply;
mapping(uint256 => EnumerableSet.AddressSet) accountsByToken;
mapping(address => EnumerableSet.UintSet) tokensByAccount;
}
bytes32 internal constant STORAGE_SLOT =
keccak256('solidstate.contracts.storage.ERC1155Enumerable');
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol";
library ABDKMath64x64Token {
using ABDKMath64x64 for int128;
/**
* @notice convert 64x64 fixed point representation of token amount to decimal
* @param value64x64 64x64 fixed point representation of token amount
* @param decimals token display decimals
* @return value decimal representation of token amount
*/
function toDecimals(int128 value64x64, uint8 decimals)
internal
pure
returns (uint256 value)
{
value = value64x64.mulu(10**decimals);
}
/**
* @notice convert decimal representation of token amount to 64x64 fixed point
* @param value decimal representation of token amount
* @param decimals token display decimals
* @return value64x64 64x64 fixed point representation of token amount
*/
function fromDecimals(uint256 value, uint8 decimals)
internal
pure
returns (int128 value64x64)
{
value64x64 = ABDKMath64x64.divu(value, 10**decimals);
}
/**
* @notice convert 64x64 fixed point representation of token amount to wei (18 decimals)
* @param value64x64 64x64 fixed point representation of token amount
* @return value wei representation of token amount
*/
function toWei(int128 value64x64) internal pure returns (uint256 value) {
value = toDecimals(value64x64, 18);
}
/**
* @notice convert wei representation (18 decimals) of token amount to 64x64 fixed point
* @param value wei representation of token amount
* @return value64x64 64x64 fixed point representation of token amount
*/
function fromWei(uint256 value) internal pure returns (int128 value64x64) {
value64x64 = fromDecimals(value, 18);
}
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol";
library OptionMath {
using ABDKMath64x64 for int128;
struct QuoteArgs {
int128 varianceAnnualized64x64; // 64x64 fixed point representation of annualized variance
int128 strike64x64; // 64x64 fixed point representation of strike price
int128 spot64x64; // 64x64 fixed point representation of spot price
int128 timeToMaturity64x64; // 64x64 fixed point representation of duration of option contract (in years)
int128 oldCLevel64x64; // 64x64 fixed point representation of C-Level of Pool before purchase
int128 oldPoolState; // 64x64 fixed point representation of current state of the pool
int128 newPoolState; // 64x64 fixed point representation of state of the pool after trade
int128 steepness64x64; // 64x64 fixed point representation of Pool state delta multiplier
int128 minAPY64x64; // 64x64 fixed point representation of minimum APY for capital locked up to underwrite options
bool isCall; // whether to price "call" or "put" option
}
struct CalculateCLevelDecayArgs {
int128 timeIntervalsElapsed64x64; // 64x64 fixed point representation of quantity of discrete arbitrary intervals elapsed since last update
int128 oldCLevel64x64; // 64x64 fixed point representation of C-Level prior to accounting for decay
int128 utilization64x64; // 64x64 fixed point representation of pool capital utilization rate
int128 utilizationLowerBound64x64;
int128 utilizationUpperBound64x64;
int128 cLevelLowerBound64x64;
int128 cLevelUpperBound64x64;
int128 cConvergenceULowerBound64x64;
int128 cConvergenceUUpperBound64x64;
}
// 64x64 fixed point integer constants
int128 internal constant ONE_64x64 = 0x10000000000000000;
int128 internal constant THREE_64x64 = 0x30000000000000000;
// 64x64 fixed point constants used in Choudhury’s approximation of the Black-Scholes CDF
int128 private constant CDF_CONST_0 = 0x09109f285df452394; // 2260 / 3989
int128 private constant CDF_CONST_1 = 0x19abac0ea1da65036; // 6400 / 3989
int128 private constant CDF_CONST_2 = 0x0d3c84b78b749bd6b; // 3300 / 3989
/**
* @notice recalculate C-Level based on change in liquidity
* @param initialCLevel64x64 64x64 fixed point representation of C-Level of Pool before update
* @param oldPoolState64x64 64x64 fixed point representation of liquidity in pool before update
* @param newPoolState64x64 64x64 fixed point representation of liquidity in pool after update
* @param steepness64x64 64x64 fixed point representation of steepness coefficient
* @return 64x64 fixed point representation of new C-Level
*/
function calculateCLevel(
int128 initialCLevel64x64,
int128 oldPoolState64x64,
int128 newPoolState64x64,
int128 steepness64x64
) external pure returns (int128) {
return
newPoolState64x64
.sub(oldPoolState64x64)
.div(
oldPoolState64x64 > newPoolState64x64
? oldPoolState64x64
: newPoolState64x64
)
.mul(steepness64x64)
.neg()
.exp()
.mul(initialCLevel64x64);
}
/**
* @notice calculate the price of an option using the Premia Finance model
* @param args arguments of quotePrice
* @return premiaPrice64x64 64x64 fixed point representation of Premia option price
* @return cLevel64x64 64x64 fixed point representation of C-Level of Pool after purchase
*/
function quotePrice(QuoteArgs memory args)
external
pure
returns (
int128 premiaPrice64x64,
int128 cLevel64x64,
int128 slippageCoefficient64x64
)
{
int128 deltaPoolState64x64 = args
.newPoolState
.sub(args.oldPoolState)
.div(args.oldPoolState)
.mul(args.steepness64x64);
int128 tradingDelta64x64 = deltaPoolState64x64.neg().exp();
int128 blackScholesPrice64x64 = _blackScholesPrice(
args.varianceAnnualized64x64,
args.strike64x64,
args.spot64x64,
args.timeToMaturity64x64,
args.isCall
);
cLevel64x64 = tradingDelta64x64.mul(args.oldCLevel64x64);
slippageCoefficient64x64 = ONE_64x64.sub(tradingDelta64x64).div(
deltaPoolState64x64
);
premiaPrice64x64 = blackScholesPrice64x64.mul(cLevel64x64).mul(
slippageCoefficient64x64
);
int128 intrinsicValue64x64;
if (args.isCall && args.strike64x64 < args.spot64x64) {
intrinsicValue64x64 = args.spot64x64.sub(args.strike64x64);
} else if (!args.isCall && args.strike64x64 > args.spot64x64) {
intrinsicValue64x64 = args.strike64x64.sub(args.spot64x64);
}
int128 collateralValue64x64 = args.isCall
? args.spot64x64
: args.strike64x64;
int128 minPrice64x64 = intrinsicValue64x64.add(
collateralValue64x64.mul(args.minAPY64x64).mul(
args.timeToMaturity64x64
)
);
if (minPrice64x64 > premiaPrice64x64) {
premiaPrice64x64 = minPrice64x64;
}
}
/**
* @notice calculate the decay of C-Level based on heat diffusion function
* @param args structured CalculateCLevelDecayArgs
* @return cLevelDecayed64x64 C-Level after accounting for decay
*/
function calculateCLevelDecay(CalculateCLevelDecayArgs memory args)
external
pure
returns (int128 cLevelDecayed64x64)
{
int128 convFHighU64x64 = (args.utilization64x64 >=
args.utilizationUpperBound64x64 &&
args.oldCLevel64x64 <= args.cLevelLowerBound64x64)
? ONE_64x64
: int128(0);
int128 convFLowU64x64 = (args.utilization64x64 <=
args.utilizationLowerBound64x64 &&
args.oldCLevel64x64 >= args.cLevelUpperBound64x64)
? ONE_64x64
: int128(0);
cLevelDecayed64x64 = args
.oldCLevel64x64
.sub(args.cConvergenceULowerBound64x64.mul(convFLowU64x64))
.sub(args.cConvergenceUUpperBound64x64.mul(convFHighU64x64))
.mul(
convFLowU64x64
.mul(ONE_64x64.sub(args.utilization64x64))
.add(convFHighU64x64.mul(args.utilization64x64))
.mul(args.timeIntervalsElapsed64x64)
.neg()
.exp()
)
.add(
args.cConvergenceULowerBound64x64.mul(convFLowU64x64).add(
args.cConvergenceUUpperBound64x64.mul(convFHighU64x64)
)
);
}
/**
* @notice calculate the exponential decay coefficient for a given interval
* @param oldTimestamp timestamp of previous update
* @param newTimestamp current timestamp
* @return 64x64 fixed point representation of exponential decay coefficient
*/
function _decay(uint256 oldTimestamp, uint256 newTimestamp)
internal
pure
returns (int128)
{
return
ONE_64x64.sub(
(-ABDKMath64x64.divu(newTimestamp - oldTimestamp, 7 days)).exp()
);
}
/**
* @notice calculate Choudhury’s approximation of the Black-Scholes CDF
* @param input64x64 64x64 fixed point representation of random variable
* @return 64x64 fixed point representation of the approximated CDF of x
*/
function _N(int128 input64x64) internal pure returns (int128) {
// squaring via mul is cheaper than via pow
int128 inputSquared64x64 = input64x64.mul(input64x64);
int128 value64x64 = (-inputSquared64x64 >> 1).exp().div(
CDF_CONST_0.add(CDF_CONST_1.mul(input64x64.abs())).add(
CDF_CONST_2.mul(inputSquared64x64.add(THREE_64x64).sqrt())
)
);
return input64x64 > 0 ? ONE_64x64.sub(value64x64) : value64x64;
}
/**
* @notice calculate the price of an option using the Black-Scholes model
* @param varianceAnnualized64x64 64x64 fixed point representation of annualized variance
* @param strike64x64 64x64 fixed point representation of strike price
* @param spot64x64 64x64 fixed point representation of spot price
* @param timeToMaturity64x64 64x64 fixed point representation of duration of option contract (in years)
* @param isCall whether to price "call" or "put" option
* @return 64x64 fixed point representation of Black-Scholes option price
*/
function _blackScholesPrice(
int128 varianceAnnualized64x64,
int128 strike64x64,
int128 spot64x64,
int128 timeToMaturity64x64,
bool isCall
) internal pure returns (int128) {
int128 cumulativeVariance64x64 = timeToMaturity64x64.mul(
varianceAnnualized64x64
);
int128 cumulativeVarianceSqrt64x64 = cumulativeVariance64x64.sqrt();
int128 d1_64x64 = spot64x64
.div(strike64x64)
.ln()
.add(cumulativeVariance64x64 >> 1)
.div(cumulativeVarianceSqrt64x64);
int128 d2_64x64 = d1_64x64.sub(cumulativeVarianceSqrt64x64);
if (isCall) {
return
spot64x64.mul(_N(d1_64x64)).sub(strike64x64.mul(_N(d2_64x64)));
} else {
return
-spot64x64.mul(_N(-d1_64x64)).sub(
strike64x64.mul(_N(-d2_64x64))
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC20 metadata interface
*/
interface IERC20Metadata {
/**
* @notice return token name
* @return token name
*/
function name() external view returns (string memory);
/**
* @notice return token symbol
* @return token symbol
*/
function symbol() external view returns (string memory);
/**
* @notice return token decimals, generally used only for display purposes
* @return token decimals
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Partial ERC20 interface needed by internal functions
*/
interface IERC20Internal {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library AddressUtils {
function toString(address account) internal pure returns (string memory) {
bytes32 value = bytes32(uint256(uint160(account)));
bytes memory alphabet = '0123456789abcdef';
bytes memory chars = new bytes(42);
chars[0] = '0';
chars[1] = 'x';
for (uint256 i = 0; i < 20; i++) {
chars[2 + i * 2] = alphabet[uint8(value[i + 12] >> 4)];
chars[3 + i * 2] = alphabet[uint8(value[i + 12] & 0x0f)];
}
return string(chars);
}
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
function sendValue(address payable account, uint256 amount) internal {
(bool success, ) = account.call{ value: amount }('');
require(success, 'AddressUtils: failed to send value');
}
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionCall(target, data, 'AddressUtils: failed low-level call');
}
function functionCall(
address target,
bytes memory data,
string memory error
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, error);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
'AddressUtils: failed low-level call with value'
);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory error
) internal returns (bytes memory) {
require(
address(this).balance >= value,
'AddressUtils: insufficient balance for call'
);
return _functionCallWithValue(target, data, value, error);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory error
) private returns (bytes memory) {
require(
isContract(target),
'AddressUtils: function call to non-contract'
);
(bool success, bytes memory returnData) = target.call{ value: value }(
data
);
if (success) {
return returnData;
} else if (returnData.length > 0) {
assembly {
let returnData_size := mload(returnData)
revert(add(32, returnData), returnData_size)
}
} else {
revert(error);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Contract ownership standard interface
* @dev see https://eips.ethereum.org/EIPS/eip-173
*/
interface IERC173 {
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @notice get the ERC173 contract owner
* @return conract owner
*/
function owner() external view returns (address);
/**
* @notice transfer contract ownership to new account
* @param account address of new owner
*/
function transferOwnership(address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library OwnableStorage {
struct Layout {
address owner;
}
bytes32 internal constant STORAGE_SLOT =
keccak256('solidstate.contracts.storage.Ownable');
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
function setOwner(Layout storage l, address owner) internal {
l.owner = owner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { EnumerableSet } from '../../../utils/EnumerableSet.sol';
import { ERC1155Base, ERC1155BaseInternal } from '../base/ERC1155Base.sol';
import { IERC1155Enumerable } from './IERC1155Enumerable.sol';
import { ERC1155EnumerableInternal, ERC1155EnumerableStorage } from './ERC1155EnumerableInternal.sol';
/**
* @title ERC1155 implementation including enumerable and aggregate functions
*/
abstract contract ERC1155Enumerable is
IERC1155Enumerable,
ERC1155Base,
ERC1155EnumerableInternal
{
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
/**
* @inheritdoc IERC1155Enumerable
*/
function totalSupply(uint256 id)
public
view
virtual
override
returns (uint256)
{
return ERC1155EnumerableStorage.layout().totalSupply[id];
}
/**
* @inheritdoc IERC1155Enumerable
*/
function totalHolders(uint256 id)
public
view
virtual
override
returns (uint256)
{
return ERC1155EnumerableStorage.layout().accountsByToken[id].length();
}
/**
* @inheritdoc IERC1155Enumerable
*/
function accountsByToken(uint256 id)
public
view
virtual
override
returns (address[] memory)
{
EnumerableSet.AddressSet storage accounts = ERC1155EnumerableStorage
.layout()
.accountsByToken[id];
address[] memory addresses = new address[](accounts.length());
for (uint256 i; i < accounts.length(); i++) {
addresses[i] = accounts.at(i);
}
return addresses;
}
/**
* @inheritdoc IERC1155Enumerable
*/
function tokensByAccount(address account)
public
view
virtual
override
returns (uint256[] memory)
{
EnumerableSet.UintSet storage tokens = ERC1155EnumerableStorage
.layout()
.tokensByAccount[account];
uint256[] memory ids = new uint256[](tokens.length());
for (uint256 i; i < tokens.length(); i++) {
ids[i] = tokens.at(i);
}
return ids;
}
/**
* @notice ERC1155 hook: update aggregate values
* @inheritdoc ERC1155EnumerableInternal
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
override(ERC1155BaseInternal, ERC1155EnumerableInternal)
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.0;
import {FeeDiscountStorage} from "./FeeDiscountStorage.sol";
interface IFeeDiscount {
event Staked(
address indexed user,
uint256 amount,
uint256 stakePeriod,
uint256 lockedUntil
);
event Unstaked(address indexed user, uint256 amount);
struct StakeLevel {
uint256 amount; // Amount to stake
uint256 discount; // Discount when amount is reached
}
/**
* @notice Stake using IERC2612 permit
* @param amount The amount of xPremia to stake
* @param period The lockup period (in seconds)
* @param deadline Deadline after which permit will fail
* @param v V
* @param r R
* @param s S
*/
function stakeWithPermit(
uint256 amount,
uint256 period,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @notice Lockup xPremia for protocol fee discounts
* Longer period of locking will apply a multiplier on the amount staked, in the fee discount calculation
* @param amount The amount of xPremia to stake
* @param period The lockup period (in seconds)
*/
function stake(uint256 amount, uint256 period) external;
/**
* @notice Unstake xPremia (If lockup period has ended)
* @param amount The amount of xPremia to unstake
*/
function unstake(uint256 amount) external;
//////////
// View //
//////////
/**
* Calculate the stake amount of a user, after applying the bonus from the lockup period chosen
* @param user The user from which to query the stake amount
* @return The user stake amount after applying the bonus
*/
function getStakeAmountWithBonus(address user)
external
view
returns (uint256);
/**
* @notice Calculate the % of fee discount for user, based on his stake
* @param user The _user for which the discount is for
* @return Percentage of protocol fee discount (in basis point)
* Ex : 1000 = 10% fee discount
*/
function getDiscount(address user) external view returns (uint256);
/**
* @notice Get stake levels
* @return Stake levels
* Ex : 2500 = -25%
*/
function getStakeLevels() external returns (StakeLevel[] memory);
/**
* @notice Get stake period multiplier
* @param period The duration (in seconds) for which tokens are locked
* @return The multiplier for this staking period
* Ex : 20000 = x2
*/
function getStakePeriodMultiplier(uint256 period)
external
returns (uint256);
/**
* @notice Get staking infos of a user
* @param user The user address for which to get staking infos
* @return The staking infos of the user
*/
function getUserInfo(address user)
external
view
returns (FeeDiscountStorage.UserInfo memory);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.0;
interface IPoolEvents {
event Purchase(
address indexed user,
uint256 longTokenId,
uint256 contractSize,
uint256 baseCost,
uint256 feeCost,
int128 spot64x64
);
event Exercise(
address indexed user,
uint256 longTokenId,
uint256 contractSize,
uint256 exerciseValue,
uint256 fee
);
event Underwrite(
address indexed underwriter,
address indexed longReceiver,
uint256 shortTokenId,
uint256 intervalContractSize,
uint256 intervalPremium,
bool isManualUnderwrite
);
event AssignExercise(
address indexed underwriter,
uint256 shortTokenId,
uint256 freedAmount,
uint256 intervalContractSize,
uint256 fee
);
event Deposit(address indexed user, bool isCallPool, uint256 amount);
event Withdrawal(
address indexed user,
bool isCallPool,
uint256 depositedAt,
uint256 amount
);
event FeeWithdrawal(bool indexed isCallPool, uint256 amount);
event Annihilate(uint256 shortTokenId, uint256 amount);
event UpdateCLevel(
bool indexed isCall,
int128 cLevel64x64,
int128 oldLiquidity64x64,
int128 newLiquidity64x64
);
event UpdateSteepness(int128 steepness64x64, bool isCallPool);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.0;
import {VolatilitySurfaceOracleStorage} from "./VolatilitySurfaceOracleStorage.sol";
interface IVolatilitySurfaceOracle {
function getWhitelistedRelayers() external view returns (address[] memory);
function getVolatilitySurface(address baseToken, address underlyingToken)
external
view
returns (VolatilitySurfaceOracleStorage.Update memory);
function getVolatilitySurfaceCoefficientsUnpacked(
address baseToken,
address underlyingToken,
bool isCall
) external view returns (int256[] memory);
function getTimeToMaturity64x64(uint64 maturity)
external
view
returns (int128);
function getAnnualizedVolatility64x64(
address baseToken,
address underlyingToken,
int128 spot64x64,
int128 strike64x64,
int128 timeToMaturity64x64,
bool isCall
) external view returns (int128);
function getBlackScholesPrice64x64(
address baseToken,
address underlyingToken,
int128 strike64x64,
int128 spot64x64,
int128 timeToMaturity64x64,
bool isCall
) external view returns (int128);
function getBlackScholesPrice(
address baseToken,
address underlyingToken,
int128 strike64x64,
int128 spot64x64,
int128 timeToMaturity64x64,
bool isCall
) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC1155 } from '../IERC1155.sol';
import { IERC1155Receiver } from '../IERC1155Receiver.sol';
import { ERC1155BaseInternal, ERC1155BaseStorage } from './ERC1155BaseInternal.sol';
/**
* @title Base ERC1155 contract
* @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license)
*/
abstract contract ERC1155Base is IERC1155, ERC1155BaseInternal {
/**
* @inheritdoc IERC1155
*/
function balanceOf(address account, uint256 id)
public
view
virtual
override
returns (uint256)
{
return _balanceOf(account, id);
}
/**
* @inheritdoc IERC1155
*/
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'
);
mapping(uint256 => mapping(address => uint256))
storage balances = ERC1155BaseStorage.layout().balances;
uint256[] memory batchBalances = new uint256[](accounts.length);
unchecked {
for (uint256 i; i < accounts.length; i++) {
require(
accounts[i] != address(0),
'ERC1155: batch balance query for the zero address'
);
batchBalances[i] = balances[ids[i]][accounts[i]];
}
}
return batchBalances;
}
/**
* @inheritdoc IERC1155
*/
function isApprovedForAll(address account, address operator)
public
view
virtual
override
returns (bool)
{
return ERC1155BaseStorage.layout().operatorApprovals[account][operator];
}
/**
* @inheritdoc IERC1155
*/
function setApprovalForAll(address operator, bool status)
public
virtual
override
{
require(
msg.sender != operator,
'ERC1155: setting approval status for self'
);
ERC1155BaseStorage.layout().operatorApprovals[msg.sender][
operator
] = status;
emit ApprovalForAll(msg.sender, operator, status);
}
/**
* @inheritdoc IERC1155
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == msg.sender || isApprovedForAll(from, msg.sender),
'ERC1155: caller is not owner nor approved'
);
_safeTransfer(msg.sender, from, to, id, amount, data);
}
/**
* @inheritdoc IERC1155
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == msg.sender || isApprovedForAll(from, msg.sender),
'ERC1155: caller is not owner nor approved'
);
_safeTransferBatch(msg.sender, from, to, ids, amounts, data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC1155 enumerable and aggregate function interface
*/
interface IERC1155Enumerable {
/**
* @notice query total minted supply of given token
* @param id token id to query
* @return token supply
*/
function totalSupply(uint256 id) external view returns (uint256);
/**
* @notice query total number of holders for given token
* @param id token id to query
* @return quantity of holders
*/
function totalHolders(uint256 id) external view returns (uint256);
/**
* @notice query holders of given token
* @param id token id to query
* @return list of holder addresses
*/
function accountsByToken(uint256 id)
external
view
returns (address[] memory);
/**
* @notice query tokens held by given address
* @param account address to query
* @return list of token ids
*/
function tokensByAccount(address account)
external
view
returns (uint256[] memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { EnumerableSet } from '../../../utils/EnumerableSet.sol';
import { ERC1155BaseInternal, ERC1155BaseStorage } from '../base/ERC1155BaseInternal.sol';
import { ERC1155EnumerableStorage } from './ERC1155EnumerableStorage.sol';
/**
* @title ERC1155Enumerable internal functions
*/
abstract contract ERC1155EnumerableInternal is ERC1155BaseInternal {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
/**
* @notice ERC1155 hook: update aggregate values
* @inheritdoc ERC1155BaseInternal
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
if (from != to) {
ERC1155EnumerableStorage.Layout storage l = ERC1155EnumerableStorage
.layout();
mapping(uint256 => EnumerableSet.AddressSet)
storage tokenAccounts = l.accountsByToken;
EnumerableSet.UintSet storage fromTokens = l.tokensByAccount[from];
EnumerableSet.UintSet storage toTokens = l.tokensByAccount[to];
for (uint256 i; i < ids.length; i++) {
uint256 amount = amounts[i];
if (amount > 0) {
uint256 id = ids[i];
if (from == address(0)) {
l.totalSupply[id] += amount;
} else if (_balanceOf(from, id) == amount) {
tokenAccounts[id].remove(from);
fromTokens.remove(id);
}
if (to == address(0)) {
l.totalSupply[id] -= amount;
} else if (_balanceOf(to, id) == 0) {
tokenAccounts[id].add(to);
toTokens.add(id);
}
}
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC1155Internal } from './IERC1155Internal.sol';
import { IERC165 } from '../../introspection/IERC165.sol';
/**
* @notice ERC1155 interface
* @dev see https://github.com/ethereum/EIPs/issues/1155
*/
interface IERC1155 is IERC1155Internal, IERC165 {
/**
* @notice query the balance of given token held by given address
* @param account address to query
* @param id token to query
* @return token balance
*/
function balanceOf(address account, uint256 id)
external
view
returns (uint256);
/**
* @notice query the balances of given tokens held by given addresses
* @param accounts addresss to query
* @param ids tokens to query
* @return token balances
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @notice query approval status of given operator with respect to given address
* @param account address to query for approval granted
* @param operator address to query for approval received
* @return whether operator is approved to spend tokens held by account
*/
function isApprovedForAll(address account, address operator)
external
view
returns (bool);
/**
* @notice grant approval to or revoke approval from given operator to spend held tokens
* @param operator address whose approval status to update
* @param status whether operator should be considered approved
*/
function setApprovalForAll(address operator, bool status) external;
/**
* @notice transfer tokens between given addresses, checking for ERC1155Receiver implementation if applicable
* @param from sender of tokens
* @param to receiver of tokens
* @param id token ID
* @param amount quantity of tokens to transfer
* @param data data payload
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @notice transfer batch of tokens between given addresses, checking for ERC1155Receiver implementation if applicable
* @param from sender of tokens
* @param to receiver of tokens
* @param ids list of token IDs
* @param amounts list of quantities of tokens to transfer
* @param data data payload
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC165 } from '../../introspection/IERC165.sol';
/**
* @title ERC1155 transfer receiver interface
*/
interface IERC1155Receiver is IERC165 {
/**
* @notice validate receipt of ERC1155 transfer
* @param operator executor of transfer
* @param from sender of tokens
* @param id token ID received
* @param value quantity of tokens received
* @param data data payload
* @return function's own selector if transfer is accepted
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @notice validate receipt of ERC1155 batch transfer
* @param operator executor of transfer
* @param from sender of tokens
* @param ids token IDs received
* @param values quantities of tokens received
* @param data data payload
* @return function's own selector if transfer is accepted
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { AddressUtils } from '../../../utils/AddressUtils.sol';
import { IERC1155Internal } from '../IERC1155Internal.sol';
import { IERC1155Receiver } from '../IERC1155Receiver.sol';
import { ERC1155BaseStorage } from './ERC1155BaseStorage.sol';
/**
* @title Base ERC1155 internal functions
* @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license)
*/
abstract contract ERC1155BaseInternal is IERC1155Internal {
using AddressUtils for address;
/**
* @notice query the balance of given token held by given address
* @param account address to query
* @param id token to query
* @return token balance
*/
function _balanceOf(address account, uint256 id)
internal
view
virtual
returns (uint256)
{
require(
account != address(0),
'ERC1155: balance query for the zero address'
);
return ERC1155BaseStorage.layout().balances[id][account];
}
/**
* @notice mint given quantity of tokens for given address
* @dev ERC1155Receiver implementation is not checked
* @param account beneficiary of minting
* @param id token ID
* @param amount quantity of tokens to mint
* @param data data payload
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(account != address(0), 'ERC1155: mint to the zero address');
_beforeTokenTransfer(
msg.sender,
address(0),
account,
_asSingletonArray(id),
_asSingletonArray(amount),
data
);
mapping(address => uint256) storage balances = ERC1155BaseStorage
.layout()
.balances[id];
balances[account] += amount;
emit TransferSingle(msg.sender, address(0), account, id, amount);
}
/**
* @notice mint given quantity of tokens for given address
* @param account beneficiary of minting
* @param id token ID
* @param amount quantity of tokens to mint
* @param data data payload
*/
function _safeMint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
_mint(account, id, amount, data);
_doSafeTransferAcceptanceCheck(
msg.sender,
address(0),
account,
id,
amount,
data
);
}
/**
* @notice mint batch of tokens for given address
* @dev ERC1155Receiver implementation is not checked
* @param account beneficiary of minting
* @param ids list of token IDs
* @param amounts list of quantities of tokens to mint
* @param data data payload
*/
function _mintBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(account != address(0), 'ERC1155: mint to the zero address');
require(
ids.length == amounts.length,
'ERC1155: ids and amounts length mismatch'
);
_beforeTokenTransfer(
msg.sender,
address(0),
account,
ids,
amounts,
data
);
mapping(uint256 => mapping(address => uint256))
storage balances = ERC1155BaseStorage.layout().balances;
for (uint256 i; i < ids.length; i++) {
balances[ids[i]][account] += amounts[i];
}
emit TransferBatch(msg.sender, address(0), account, ids, amounts);
}
/**
* @notice mint batch of tokens for given address
* @param account beneficiary of minting
* @param ids list of token IDs
* @param amounts list of quantities of tokens to mint
* @param data data payload
*/
function _safeMintBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
_mintBatch(account, ids, amounts, data);
_doSafeBatchTransferAcceptanceCheck(
msg.sender,
address(0),
account,
ids,
amounts,
data
);
}
/**
* @notice burn given quantity of tokens held by given address
* @param account holder of tokens to burn
* @param id token ID
* @param amount quantity of tokens to burn
*/
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(account != address(0), 'ERC1155: burn from the zero address');
_beforeTokenTransfer(
msg.sender,
account,
address(0),
_asSingletonArray(id),
_asSingletonArray(amount),
''
);
mapping(address => uint256) storage balances = ERC1155BaseStorage
.layout()
.balances[id];
unchecked {
require(
balances[account] >= amount,
'ERC1155: burn amount exceeds balances'
);
balances[account] -= amount;
}
emit TransferSingle(msg.sender, account, address(0), id, amount);
}
/**
* @notice burn given batch of tokens held by given address
* @param account holder of tokens to burn
* @param ids token IDs
* @param amounts quantities of tokens to burn
*/
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'
);
_beforeTokenTransfer(msg.sender, account, address(0), ids, amounts, '');
mapping(uint256 => mapping(address => uint256))
storage balances = ERC1155BaseStorage.layout().balances;
unchecked {
for (uint256 i; i < ids.length; i++) {
uint256 id = ids[i];
require(
balances[id][account] >= amounts[i],
'ERC1155: burn amount exceeds balance'
);
balances[id][account] -= amounts[i];
}
}
emit TransferBatch(msg.sender, account, address(0), ids, amounts);
}
/**
* @notice transfer tokens between given addresses
* @dev ERC1155Receiver implementation is not checked
* @param operator executor of transfer
* @param sender sender of tokens
* @param recipient receiver of tokens
* @param id token ID
* @param amount quantity of tokens to transfer
* @param data data payload
*/
function _transfer(
address operator,
address sender,
address recipient,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(
recipient != address(0),
'ERC1155: transfer to the zero address'
);
_beforeTokenTransfer(
operator,
sender,
recipient,
_asSingletonArray(id),
_asSingletonArray(amount),
data
);
mapping(uint256 => mapping(address => uint256))
storage balances = ERC1155BaseStorage.layout().balances;
unchecked {
uint256 senderBalance = balances[id][sender];
require(
senderBalance >= amount,
'ERC1155: insufficient balances for transfer'
);
balances[id][sender] = senderBalance - amount;
}
balances[id][recipient] += amount;
emit TransferSingle(operator, sender, recipient, id, amount);
}
/**
* @notice transfer tokens between given addresses
* @param operator executor of transfer
* @param sender sender of tokens
* @param recipient receiver of tokens
* @param id token ID
* @param amount quantity of tokens to transfer
* @param data data payload
*/
function _safeTransfer(
address operator,
address sender,
address recipient,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
_transfer(operator, sender, recipient, id, amount, data);
_doSafeTransferAcceptanceCheck(
operator,
sender,
recipient,
id,
amount,
data
);
}
/**
* @notice transfer batch of tokens between given addresses
* @dev ERC1155Receiver implementation is not checked
* @param operator executor of transfer
* @param sender sender of tokens
* @param recipient receiver of tokens
* @param ids token IDs
* @param amounts quantities of tokens to transfer
* @param data data payload
*/
function _transferBatch(
address operator,
address sender,
address recipient,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(
recipient != address(0),
'ERC1155: transfer to the zero address'
);
require(
ids.length == amounts.length,
'ERC1155: ids and amounts length mismatch'
);
_beforeTokenTransfer(operator, sender, recipient, ids, amounts, data);
mapping(uint256 => mapping(address => uint256))
storage balances = ERC1155BaseStorage.layout().balances;
for (uint256 i; i < ids.length; i++) {
uint256 token = ids[i];
uint256 amount = amounts[i];
unchecked {
uint256 senderBalance = balances[token][sender];
require(
senderBalance >= amount,
'ERC1155: insufficient balances for transfer'
);
balances[token][sender] = senderBalance - amount;
}
balances[token][recipient] += amount;
}
emit TransferBatch(operator, sender, recipient, ids, amounts);
}
/**
* @notice transfer batch of tokens between given addresses
* @param operator executor of transfer
* @param sender sender of tokens
* @param recipient receiver of tokens
* @param ids token IDs
* @param amounts quantities of tokens to transfer
* @param data data payload
*/
function _safeTransferBatch(
address operator,
address sender,
address recipient,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
_transferBatch(operator, sender, recipient, ids, amounts, data);
_doSafeBatchTransferAcceptanceCheck(
operator,
sender,
recipient,
ids,
amounts,
data
);
}
/**
* @notice wrap given element in array of length 1
* @param element element to wrap
* @return singleton array
*/
function _asSingletonArray(uint256 element)
private
pure
returns (uint256[] memory)
{
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
/**
* @notice revert if applicable transfer recipient is not valid ERC1155Receiver
* @param operator executor of transfer
* @param from sender of tokens
* @param to receiver of tokens
* @param id token ID
* @param amount quantity of tokens to transfer
* @param data data payload
*/
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) {
require(
response == IERC1155Receiver.onERC1155Received.selector,
'ERC1155: ERC1155Receiver rejected tokens'
);
} catch Error(string memory reason) {
revert(reason);
} catch {
revert('ERC1155: transfer to non ERC1155Receiver implementer');
}
}
}
/**
* @notice revert if applicable transfer recipient is not valid ERC1155Receiver
* @param operator executor of transfer
* @param from sender of tokens
* @param to receiver of tokens
* @param ids token IDs
* @param amounts quantities of tokens to transfer
* @param data data payload
*/
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) {
require(
response ==
IERC1155Receiver.onERC1155BatchReceived.selector,
'ERC1155: ERC1155Receiver rejected tokens'
);
} catch Error(string memory reason) {
revert(reason);
} catch {
revert('ERC1155: transfer to non ERC1155Receiver implementer');
}
}
}
/**
* @notice ERC1155 hook, called before all transfers including mint and burn
* @dev function should be overridden and new implementation must call super
* @dev called for both single and batch transfers
* @param operator executor of transfer
* @param from sender of tokens
* @param to receiver of tokens
* @param ids token IDs
* @param amounts quantities of tokens to transfer
* @param data data payload
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC165 } from '../../introspection/IERC165.sol';
/**
* @notice Partial ERC1155 interface needed by internal functions
*/
interface IERC1155Internal {
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
event ApprovalForAll(
address indexed account,
address indexed operator,
bool approved
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC165 interface registration interface
* @dev see https://eips.ethereum.org/EIPS/eip-165
*/
interface IERC165 {
/**
* @notice query whether contract has registered support for given interface
* @param interfaceId interface id
* @return bool whether interface is supported
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library ERC1155BaseStorage {
struct Layout {
mapping(uint256 => mapping(address => uint256)) balances;
mapping(address => mapping(address => bool)) operatorApprovals;
}
bytes32 internal constant STORAGE_SLOT =
keccak256('solidstate.contracts.storage.ERC1155Base');
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
library FeeDiscountStorage {
bytes32 internal constant STORAGE_SLOT =
keccak256("premia.contracts.staking.PremiaFeeDiscount");
struct UserInfo {
uint256 balance; // Balance staked by user
uint64 stakePeriod; // Stake period selected by user
uint64 lockedUntil; // Timestamp at which the lock ends
}
struct Layout {
// User data with xPREMIA balance staked and date at which lock ends
mapping(address => UserInfo) userInfo;
}
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
library PremiaMiningStorage {
bytes32 internal constant STORAGE_SLOT =
keccak256("premia.contracts.storage.PremiaMining");
// Info of each pool.
struct PoolInfo {
uint256 allocPoint; // How many allocation points assigned to this pool. PREMIA to distribute per block.
uint256 lastRewardTimestamp; // Last timestamp that PREMIA distribution occurs
uint256 accPremiaPerShare; // Accumulated PREMIA per share, times 1e12. See below.
}
// Info of each user.
struct UserInfo {
uint256 reward; // Total allocated unclaimed reward
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of PREMIA
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accPremiaPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accPremiaPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
struct Layout {
// Total PREMIA left to distribute
uint256 premiaAvailable;
// Amount of premia distributed per year
uint256 premiaPerYear;
// pool -> isCallPool -> PoolInfo
mapping(address => mapping(bool => PoolInfo)) poolInfo;
// pool -> isCallPool -> user -> UserInfo
mapping(address => mapping(bool => mapping(address => UserInfo))) userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 totalAllocPoint;
}
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {EnumerableSet} from "@solidstate/contracts/utils/EnumerableSet.sol";
library VolatilitySurfaceOracleStorage {
bytes32 internal constant STORAGE_SLOT =
keccak256("premia.contracts.storage.VolatilitySurfaceOracle");
uint256 internal constant COEFF_BITS = 51;
uint256 internal constant COEFF_BITS_MINUS_ONE = 50;
uint256 internal constant COEFF_AMOUNT = 5;
// START_BIT = COEFF_BITS * (COEFF_AMOUNT - 1)
uint256 internal constant START_BIT = 204;
struct Update {
uint256 updatedAt;
bytes32 callCoefficients;
bytes32 putCoefficients;
}
struct Layout {
// Base token -> Underlying token -> Update
mapping(address => mapping(address => Update)) volatilitySurfaces;
// Relayer addresses which can be trusted to provide accurate option trades
EnumerableSet.AddressSet whitelistedRelayers;
}
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
function getCoefficients(
Layout storage l,
address baseToken,
address underlyingToken,
bool isCall
) internal view returns (bytes32) {
Update storage u = l.volatilitySurfaces[baseToken][underlyingToken];
return isCall ? u.callCoefficients : u.putCoefficients;
}
function parseVolatilitySurfaceCoefficients(bytes32 input)
internal
pure
returns (int256[] memory coefficients)
{
coefficients = new int256[](COEFF_AMOUNT);
// Value to add to negative numbers to cast them to int256
int256 toAdd = (int256(-1) >> COEFF_BITS) << COEFF_BITS;
assembly {
let i := 0
// Value equal to -1
let mid := shl(COEFF_BITS_MINUS_ONE, 1)
for {
} lt(i, COEFF_AMOUNT) {
} {
let offset := sub(START_BIT, mul(COEFF_BITS, i))
let coeff := shr(
offset,
sub(
input,
shl(
add(offset, COEFF_BITS),
shr(add(offset, COEFF_BITS), input)
)
)
)
// Check if value is a negative number and needs casting
if or(eq(coeff, mid), gt(coeff, mid)) {
coeff := add(coeff, toAdd)
}
// Store result in the coefficients array
mstore(add(coefficients, add(0x20, mul(0x20, i))), coeff)
i := add(i, 1)
}
}
}
function formatVolatilitySurfaceCoefficients(int256[5] memory coefficients)
internal
pure
returns (bytes32 result)
{
for (uint256 i = 0; i < COEFF_AMOUNT; i++) {
int256 max = int256(1 << COEFF_BITS_MINUS_ONE);
require(
coefficients[i] < max && coefficients[i] > -max,
"Out of bounds"
);
}
assembly {
let i := 0
for {
} lt(i, COEFF_AMOUNT) {
} {
let offset := sub(START_BIT, mul(COEFF_BITS, i))
let coeff := mload(add(coefficients, mul(0x20, i)))
result := add(
result,
shl(
offset,
sub(coeff, shl(COEFF_BITS, shr(COEFF_BITS, coeff)))
)
)
i := add(i, 1)
}
}
}
}
|
get current C-Level, without accounting for pending adjustments l storage layout struct isCall whether query is for call or put pool return cLevel64x64 64x64 fixed point representation of C-Level/
|
function getRawCLevel64x64(Layout storage l, bool isCall)
internal
view
returns (int128 cLevel64x64)
{
cLevel64x64 = isCall ? l.cLevelUnderlying64x64 : l.cLevelBase64x64;
}
| 103,896 |
pragma solidity ^0.4.18;
/**
* Changes by https://www.docademic.com/
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Destroyable is Ownable{
/**
* @notice Allows to destroy the contract and return the tokens to the owner.
*/
function destroy() public onlyOwner{
selfdestruct(owner);
}
}
interface Token {
function transfer(address _to, uint256 _value) public;
function balanceOf(address who) public returns (uint256);
}
contract MultiVesting is Ownable, Destroyable {
using SafeMath for uint256;
// beneficiary of tokens
struct Beneficiary {
uint256 released;
uint256 vested;
uint256 start;
uint256 cliff;
uint256 duration;
bool revoked;
bool revocable;
bool isBeneficiary;
}
event Released(address _beneficiary, uint256 amount);
event Revoked(address _beneficiary);
event NewBeneficiary(address _beneficiary);
event BeneficiaryDestroyed(address _beneficiary);
mapping(address => Beneficiary) public beneficiaries;
Token public token;
uint256 public totalVested;
uint256 public totalReleased;
/*
* Modifiers
*/
modifier isNotBeneficiary(address _beneficiary) {
require(!beneficiaries[_beneficiary].isBeneficiary);
_;
}
modifier isBeneficiary(address _beneficiary) {
require(beneficiaries[_beneficiary].isBeneficiary);
_;
}
modifier wasRevoked(address _beneficiary) {
require(beneficiaries[_beneficiary].revoked);
_;
}
modifier wasNotRevoked(address _beneficiary) {
require(!beneficiaries[_beneficiary].revoked);
_;
}
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _token address of the token of vested tokens
*/
function MultiVesting(address _token) public {
require(_token != address(0));
token = Token(_token);
}
function() payable public {
release(msg.sender);
}
/**
* @notice Transfers vested tokens to beneficiary (alternative to fallback function).
*/
function release() public {
release(msg.sender);
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param _beneficiary Beneficiary address
*/
function release(address _beneficiary) private
isBeneficiary(_beneficiary)
{
Beneficiary storage beneficiary = beneficiaries[_beneficiary];
uint256 unreleased = releasableAmount(_beneficiary);
require(unreleased > 0);
beneficiary.released = beneficiary.released.add(unreleased);
totalReleased = totalReleased.add(unreleased);
token.transfer(_beneficiary, unreleased);
if((beneficiary.vested - beneficiary.released) == 0){
beneficiary.isBeneficiary = false;
}
Released(_beneficiary, unreleased);
}
/**
* @notice Allows the owner to transfers vested tokens to beneficiary.
* @param _beneficiary Beneficiary address
*/
function releaseTo(address _beneficiary) public onlyOwner {
release(_beneficiary);
}
/**
* @dev Add new beneficiary to start vesting
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _start time in seconds which the tokens will vest
* @param _cliff time in seconds of the cliff in which tokens will begin to vest
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
function addBeneficiary(address _beneficiary, uint256 _vested, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable)
onlyOwner
isNotBeneficiary(_beneficiary)
public {
require(_beneficiary != address(0));
require(_cliff >= _start);
require(token.balanceOf(this) >= totalVested.sub(totalReleased).add(_vested));
beneficiaries[_beneficiary] = Beneficiary({
released : 0,
vested : _vested,
start : _start,
cliff : _cliff,
duration : _duration,
revoked : false,
revocable : _revocable,
isBeneficiary : true
});
totalVested = totalVested.add(_vested);
NewBeneficiary(_beneficiary);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param _beneficiary Beneficiary address
*/
function revoke(address _beneficiary) public onlyOwner {
Beneficiary storage beneficiary = beneficiaries[_beneficiary];
require(beneficiary.revocable);
require(!beneficiary.revoked);
uint256 balance = beneficiary.vested.sub(beneficiary.released);
uint256 unreleased = releasableAmount(_beneficiary);
uint256 refund = balance.sub(unreleased);
token.transfer(owner, refund);
totalReleased = totalReleased.add(refund);
beneficiary.revoked = true;
beneficiary.released = beneficiary.released.add(refund);
Revoked(_beneficiary);
}
/**
* @notice Allows the owner to destroy a beneficiary. Remain tokens are returned to the owner.
* @param _beneficiary Beneficiary address
*/
function destroyBeneficiary(address _beneficiary) public onlyOwner {
Beneficiary storage beneficiary = beneficiaries[_beneficiary];
uint256 balance = beneficiary.vested.sub(beneficiary.released);
token.transfer(owner, balance);
totalReleased = totalReleased.add(balance);
beneficiary.isBeneficiary = false;
beneficiary.released = beneficiary.released.add(balance);
BeneficiaryDestroyed(_beneficiary);
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param _beneficiary Beneficiary address
*/
function releasableAmount(address _beneficiary) public view returns (uint256) {
return vestedAmount(_beneficiary).sub(beneficiaries[_beneficiary].released);
}
/**
* @dev Calculates the amount that has already vested.
* @param _beneficiary Beneficiary address
*/
function vestedAmount(address _beneficiary) public view returns (uint256) {
Beneficiary storage beneficiary = beneficiaries[_beneficiary];
uint256 totalBalance = beneficiary.vested;
if (now < beneficiary.cliff) {
return 0;
} else if (now >= beneficiary.start.add(beneficiary.duration) || beneficiary.revoked) {
return totalBalance;
} else {
return totalBalance.mul(now.sub(beneficiary.start)).div(beneficiary.duration);
}
}
/**
* @notice Allows the owner to flush the eth.
*/
function flushEth() public onlyOwner {
owner.transfer(this.balance);
}
/**
* @notice Allows the owner to destroy the contract and return the tokens to the owner.
*/
function destroy() public onlyOwner {
token.transfer(owner, token.balanceOf(this));
selfdestruct(owner);
}
}
|
Allows the owner to revoke the vesting. Tokens already vested remain in the contract, the rest are returned to the owner. _beneficiary Beneficiary address/
|
function revoke(address _beneficiary) public onlyOwner {
Beneficiary storage beneficiary = beneficiaries[_beneficiary];
require(beneficiary.revocable);
require(!beneficiary.revoked);
uint256 balance = beneficiary.vested.sub(beneficiary.released);
uint256 unreleased = releasableAmount(_beneficiary);
uint256 refund = balance.sub(unreleased);
token.transfer(owner, refund);
totalReleased = totalReleased.add(refund);
beneficiary.revoked = true;
beneficiary.released = beneficiary.released.add(refund);
Revoked(_beneficiary);
}
| 2,328,984 |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
interface ICurvePairs {
function add_liquidity(uint256[2] memory _amounts, uint256 _min_mint_amount) external;
function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 _min_amount) external;
function balances(uint256 i) external view returns (uint256);
}
interface IGauge {
function balanceOf(address _address) external view returns (uint256);
function deposit(uint256 _amount) external;
function withdraw(uint256 _amount) external;
function getReward() external; // For Pickle Farm only
}
interface IMintr {
function mint(address _address) external;
}
interface IRouter {
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB, uint256 liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint[] memory amounts);
function getAmountsOut(uint256 amountIn, address[] memory path) external view returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
}
interface IPickleJar is IERC20 {
function deposit(uint256 _amount) external;
function withdraw(uint256 _amount) external;
function balance() external view returns (uint256);
}
interface IMasterChef {
function deposit(uint256 _pid, uint256 _amount) external;
function withdraw(uint256 _pid, uint256 _amount) external;
function userInfo(uint256, address) external view returns(uint256, uint256);
}
interface IWETH is IERC20 {
function withdraw(uint256 _amount) external;
}
interface ICitadelVault {
function getReimburseTokenAmount(uint256) external view returns (uint256);
}
interface IChainlink {
function latestAnswer() external view returns (int256);
}
interface ISLPToken is IERC20 {
function getReserves() external view returns (uint112, uint112, uint32);
}
contract CitadelStrategy is Ownable {
using SafeERC20 for IERC20;
using SafeERC20 for IWETH;
using SafeERC20 for IPickleJar;
using SafeERC20 for ISLPToken;
using SafeMath for uint256;
IERC20 private constant WBTC = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
IWETH private constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IERC20 private constant USDT = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 private constant USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IERC20 private constant DAI = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
IRouter private constant router = IRouter(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // SushiSwap
ICitadelVault public vault;
// Curve
ICurvePairs private constant cPairs = ICurvePairs(0x4CA9b3063Ec5866A4B82E437059D2C43d1be596F); // HBTC/WBTC
IERC20 private constant clpToken = IERC20(0xb19059ebb43466C323583928285a49f558E572Fd);
IERC20 private constant CRV = IERC20(0xD533a949740bb3306d119CC777fa900bA034cd52);
IGauge private constant gaugeC = IGauge(0x4c18E409Dc8619bFb6a1cB56D114C3f592E0aE79);
IMintr private constant mintr = IMintr(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0);
// Pickle
ISLPToken private constant slpWBTC = ISLPToken(0xCEfF51756c56CeFFCA006cD410B03FFC46dd3a58); // WBTC/ETH
ISLPToken private constant slpDAI = ISLPToken(0xC3D03e4F041Fd4cD388c549Ee2A29a9E5075882f); // DAI/ETH
IERC20 private constant PICKLE = IERC20(0x429881672B9AE42b8EbA0E26cD9C73711b891Ca5);
IPickleJar private constant pickleJarWBTC = IPickleJar(0xde74b6c547bd574c3527316a2eE30cd8F6041525);
IPickleJar private constant pickleJarDAI = IPickleJar(0x55282dA27a3a02ffe599f6D11314D239dAC89135);
IGauge private constant gaugeP_WBTC = IGauge(0xD55331E7bCE14709d825557E5Bca75C73ad89bFb);
IGauge private constant gaugeP_DAI = IGauge(0x6092c7084821057060ce2030F9CC11B22605955F);
// Sushiswap Onsen
IERC20 private constant DPI = IERC20(0x1494CA1F11D487c2bBe4543E90080AeBa4BA3C2b);
ISLPToken private constant slpDPI = ISLPToken(0x34b13F8CD184F55d0Bd4Dd1fe6C07D46f245c7eD); // DPI/ETH
IERC20 private constant SUSHI = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2);
IMasterChef private constant masterChef = IMasterChef(0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd);
// LP token price in ETH
uint256 private _HBTCWBTCLPTokenPrice;
uint256 private _WBTCETHLPTokenPrice;
uint256 private _DPIETHLPTokenPrice;
uint256 private _DAIETHLPTokenPrice;
// Pool in ETH
uint256 private _poolHBTCWBTC;
uint256 private _poolWBTCETH;
uint256 private _poolDPIETH;
uint256 private _poolDAIETH;
uint256 private _pool; // For emergencyWithdraw() only
// Others
uint256 private constant DENOMINATOR = 10000;
bool public isVesting;
// Fees
uint256 public yieldFeePerc = 1000;
address public admin;
address public communityWallet;
address public strategist;
event ETHToInvest(uint256 amount);
event LatestLPTokenPrice(uint256 curveHBTC, uint256 pickleWBTC, uint256 sushiSwapDPI, uint256 pickleDAI);
event YieldAmount(uint256 curveHBTC, uint256 pickleWBTC, uint256 sushiSwapDPI, uint256 pickleDAI); // in ETH
event CurrentComposition(uint256 curveHBTC, uint256 pickleWBTC, uint256 sushiSwapDPI, uint256 pickleDAI); // in ETH
event TargetComposition(uint256 curveHBTC, uint256 pickleWBTC, uint256 sushiSwapDPI, uint256 pickleDAI); // in ETH
event AddLiquidity(address pairs, uint256 amountA, uint256 amountB, uint256 lpTokenMinted); // in ETH
modifier onlyVault {
require(msg.sender == address(vault), "Only vault");
_;
}
constructor(address _communityWallet, address _strategist, address _admin) {
communityWallet = _communityWallet;
strategist = _strategist;
admin = _admin;
// Sushiswap router
WETH.safeApprove(address(router), type(uint256).max);
WBTC.safeApprove(address(router), type(uint256).max);
DAI.safeApprove(address(router), type(uint256).max);
slpWBTC.safeApprove(address(router), type(uint256).max);
slpDAI.safeApprove(address(router), type(uint256).max);
slpDPI.safeApprove(address(router), type(uint256).max);
CRV.safeApprove(address(router), type(uint256).max);
PICKLE.safeApprove(address(router), type(uint256).max);
SUSHI.safeApprove(address(router), type(uint256).max);
// Curve
WBTC.safeApprove(address(cPairs), type(uint256).max);
clpToken.safeApprove(address(gaugeC), type(uint256).max);
// Pickle
slpWBTC.safeApprove(address(pickleJarWBTC), type(uint256).max);
slpDAI.safeApprove(address(pickleJarDAI), type(uint256).max);
pickleJarWBTC.safeApprove(address(gaugeP_WBTC), type(uint256).max);
pickleJarDAI.safeApprove(address(gaugeP_DAI), type(uint256).max);
// Sushiswap Onsen
DPI.safeApprove(address(router), type(uint256).max);
slpDPI.safeApprove(address(masterChef), type(uint256).max);
// Set first LP tokens price
(uint256 _clpTokenPriceHBTC, uint256 _pSlpTokenPriceWBTC, uint256 _slpTokenPriceDPI, uint256 _pSlpTokenPriceDAI) = _getLPTokenPrice();
_HBTCWBTCLPTokenPrice = _clpTokenPriceHBTC;
_WBTCETHLPTokenPrice = _pSlpTokenPriceWBTC;
_DPIETHLPTokenPrice = _slpTokenPriceDPI;
_DAIETHLPTokenPrice = _pSlpTokenPriceDAI;
}
/// @notice Function to set vault address that interact with this contract. This function only execute once when deployment
/// @param _address Address of vault contract
function setVault(address _address) external onlyOwner {
require(address(vault) == address(0), "Vault set");
vault = ICitadelVault(_address);
}
/// @notice Function to invest new funds to farms based on composition
/// @param _amount Amount to invest in ETH
function invest(uint256 _amount) external onlyVault {
_updatePoolForPriceChange();
WETH.safeTransferFrom(address(vault), address(this), _amount);
emit ETHToInvest(_amount);
_updatePoolForProvideLiquidity();
}
/// @notice Function to update pool balance because of price change of corresponding LP token
function _updatePoolForPriceChange() private {
(uint256 _clpTokenPriceHBTC, uint256 _pSlpTokenPriceWBTC, uint256 _slpTokenPriceDPI, uint256 _pSlpTokenPriceDAI) = _getLPTokenPrice();
_poolHBTCWBTC = _poolHBTCWBTC.mul(_clpTokenPriceHBTC).div(_HBTCWBTCLPTokenPrice);
_poolWBTCETH = _poolWBTCETH.mul(_pSlpTokenPriceWBTC).div(_WBTCETHLPTokenPrice);
_poolDPIETH = _poolDPIETH.mul(_slpTokenPriceDPI).div(_DPIETHLPTokenPrice);
_poolDAIETH = _poolDAIETH.mul(_pSlpTokenPriceDAI).div(_DAIETHLPTokenPrice);
emit CurrentComposition(_poolHBTCWBTC, _poolWBTCETH, _poolDPIETH, _poolDAIETH);
// Update new LP token price
_HBTCWBTCLPTokenPrice = _clpTokenPriceHBTC;
_WBTCETHLPTokenPrice = _pSlpTokenPriceWBTC;
_DPIETHLPTokenPrice = _slpTokenPriceDPI;
_DAIETHLPTokenPrice = _pSlpTokenPriceDAI;
emit LatestLPTokenPrice(_HBTCWBTCLPTokenPrice, _WBTCETHLPTokenPrice, _DPIETHLPTokenPrice, _DAIETHLPTokenPrice);
}
/// @notice Function to harvest rewards from farms and reinvest into farms based on composition
function yield() external onlyVault {
_updatePoolForPriceChange();
uint256[] memory _yieldAmts = new uint256[](4); // For emit yield amount of each farm
// 1) Claim all rewards
uint256 _yieldFees;
// Curve HBTC/WBTC
mintr.mint(address(gaugeC)); // Claim CRV
uint256 _balanceOfCRV = CRV.balanceOf(address(this));
if (_balanceOfCRV > 0) {
uint256[] memory _amounts = _swapExactTokensForTokens(address(CRV), address(WETH), _balanceOfCRV);
_yieldAmts[0] = _amounts[1];
uint256 _fee = _amounts[1].mul(yieldFeePerc).div(DENOMINATOR);
_poolHBTCWBTC = _poolHBTCWBTC.add(_amounts[1].sub(_fee));
_yieldFees = _yieldFees.add(_fee);
}
// Pickle WBTC/ETH
gaugeP_WBTC.getReward(); // Claim PICKLE
uint256 _balanceOfPICKLEForWETH = PICKLE.balanceOf(address(this));
if (_balanceOfPICKLEForWETH > 0) {
uint256[] memory _amounts = _swapExactTokensForTokens(address(PICKLE), address(WETH), _balanceOfPICKLEForWETH);
_yieldAmts[1] = _amounts[1];
uint256 _fee = _amounts[1].mul(yieldFeePerc).div(DENOMINATOR);
_poolWBTCETH = _poolWBTCETH.add(_amounts[1].sub(_fee));
_yieldFees = _yieldFees.add(_fee);
}
// Sushiswap DPI/ETH
(uint256 _slpDPIAmt,) = masterChef.userInfo(42, address(this));
if (_slpDPIAmt > 0) {
// SushiSwap previous SUSHI reward is auto harvest after new deposit
// Swap SUSHI to WETH
uint256 _balanceOfSUSHI = SUSHI.balanceOf(address(this));
if (_balanceOfSUSHI > 0) {
uint256[] memory _amounts = _swapExactTokensForTokens(address(SUSHI), address(WETH), _balanceOfSUSHI);
uint256 _fee = _amounts[1].mul(yieldFeePerc).div(DENOMINATOR);
_yieldAmts[2] = _amounts[1];
_poolDPIETH = _poolDPIETH.add(_amounts[1].sub(_fee));
_yieldFees = _yieldFees.add(_fee);
}
}
// Pickle DAI/ETH
gaugeP_DAI.getReward(); // Claim PICKLE
uint256 _balanceOfPICKLEForDAI = PICKLE.balanceOf(address(this));
if (_balanceOfPICKLEForDAI > 0) {
uint256[] memory _amounts = _swapExactTokensForTokens(address(PICKLE), address(WETH), _balanceOfPICKLEForDAI);
_yieldAmts[3] = _amounts[1];
uint256 _fee = _amounts[1].mul(yieldFeePerc).div(DENOMINATOR);
_poolDAIETH = _poolDAIETH.add(_amounts[1].sub(_fee));
_yieldFees = _yieldFees.add(_fee);
}
emit YieldAmount(_yieldAmts[0], _yieldAmts[1], _yieldAmts[2], _yieldAmts[3]);
// 2) Split yield fees
_splitYieldFees(_yieldFees);
// 3) Reinvest rewards
_updatePoolForProvideLiquidity();
}
/// @notice Function to transfer fees that collect from yield to wallets
/// @param _amount Fees to transfer in ETH
function _splitYieldFees(uint256 _amount) private {
WETH.withdraw(_amount);
uint256 _yieldFee = (address(this).balance).mul(2).div(5);
(bool _a,) = admin.call{value: _yieldFee}(""); // 40%
require(_a);
(bool _t,) = communityWallet.call{value: _yieldFee}(""); // 40%
require(_t);
(bool _s,) = strategist.call{value: (address(this).balance)}(""); // 20%
require(_s);
}
// To enable receive ETH from WETH in _splitYieldFees()
receive() external payable {}
/// @notice Function to provide liquidity into farms and update pool of each farms
function _updatePoolForProvideLiquidity() private {
uint256 _totalPool = _getTotalPool().add(WETH.balanceOf(address(this)));
// Calculate target composition for each farm
uint256 _thirtyPercOfPool = _totalPool.mul(3000).div(DENOMINATOR);
uint256 _poolHBTCWBTCTarget = _thirtyPercOfPool; // 30% for Curve HBTC/WBTC
uint256 _poolWBTCETHTarget = _thirtyPercOfPool; // 30% for Pickle WBTC/ETH
uint256 _poolDPIETHTarget = _thirtyPercOfPool; // 30% for SushiSwap DPI/ETH
uint256 _poolDAIETHTarget = _totalPool.sub(_thirtyPercOfPool).sub(_thirtyPercOfPool).sub(_thirtyPercOfPool); // 10% for Pickle DAI/ETH
emit CurrentComposition(_poolHBTCWBTC, _poolWBTCETH, _poolDPIETH, _poolDAIETH);
emit TargetComposition(_poolHBTCWBTCTarget, _poolWBTCETHTarget, _poolDPIETHTarget, _poolDAIETHTarget);
// If there is no negative value(need to remove liquidity from farm in order to drive back the composition)
// We proceed with split funds into 4 farms and drive composition back to target
// Else, we put all the funds into the farm that is furthest from target composition
if (
_poolHBTCWBTCTarget > _poolHBTCWBTC &&
_poolWBTCETHTarget > _poolWBTCETH &&
_poolDPIETHTarget > _poolDPIETH &&
_poolDAIETHTarget > _poolDAIETH
) {
// invest funds into Curve HBTC/WBTC
uint256 _investHBTCWBTCAmt = _poolHBTCWBTCTarget.sub(_poolHBTCWBTC);
_investHBTCWBTC(_investHBTCWBTCAmt);
// invest funds into Pickle WBTC/ETH
uint256 _investWBTCETHAmt = _poolWBTCETHTarget.sub(_poolWBTCETH);
_investWBTCETH(_investWBTCETHAmt);
// invest funds into Sushiswap Onsen DPI/ETH
uint256 _investDPIETHAmt = _poolDPIETHTarget.sub(_poolDPIETH);
_investDPIETH(_investDPIETHAmt);
// invest funds into Pickle DAI/ETH
uint256 _investDAIETHAmt = _poolDAIETHTarget.sub(_poolDAIETH);
_investDAIETH(_investDAIETHAmt);
} else {
// Put all the yield into the farm that is furthest from target composition
uint256 _furthest;
uint256 _farmIndex;
// 1. Find out the farm that is furthest from target composition
if (_poolHBTCWBTCTarget > _poolHBTCWBTC) {
uint256 _diff = _poolHBTCWBTCTarget.sub(_poolHBTCWBTC);
_furthest = _diff;
_farmIndex = 0;
}
if (_poolWBTCETHTarget > _poolWBTCETH) {
uint256 _diff = _poolWBTCETHTarget.sub(_poolWBTCETH);
if (_diff > _furthest) {
_furthest = _diff;
_farmIndex = 1;
}
}
if (_poolDPIETHTarget > _poolDPIETH) {
uint256 _diff = _poolDPIETHTarget.sub(_poolDPIETH);
if (_diff > _furthest) {
_furthest = _diff;
_farmIndex = 2;
}
}
if (_poolDAIETHTarget > _poolDAIETH) {
uint256 _diff = _poolDAIETHTarget.sub(_poolDAIETH);
if (_diff > _furthest) {
_furthest = _diff;
_farmIndex = 3;
}
}
// 2. Put all the funds into the farm that is furthest from target composition
uint256 _balanceOfWETH = WETH.balanceOf(address(this));
if (_farmIndex == 0) {
_investHBTCWBTC(_balanceOfWETH);
} else if (_farmIndex == 1) {
_investWBTCETH(_balanceOfWETH);
} else if (_farmIndex == 2) {
_investDPIETH(_balanceOfWETH);
} else {
_investDAIETH(_balanceOfWETH);
}
}
emit CurrentComposition(_poolHBTCWBTC, _poolWBTCETH, _poolDPIETH, _poolDAIETH);
}
/// @notice Function to invest funds into Curve HBTC/WBTC pool
/// @notice and stake Curve LP token into Curve Gauge(staking contract)
/// @param _amount Amount to invest in ETH
function _investHBTCWBTC(uint256 _amount) private {
uint256[] memory _amounts = _swapExactTokensForTokens(address(WETH), address(WBTC), _amount);
if (_amounts[1] > 0) {
cPairs.add_liquidity([0, _amounts[1]], 0);
uint256 _balanceOfClpToken = clpToken.balanceOf(address(this));
gaugeC.deposit(_balanceOfClpToken);
_poolHBTCWBTC = _poolHBTCWBTC.add(_amount);
emit AddLiquidity(address(cPairs), _amounts[1], 0, _balanceOfClpToken);
}
}
/// @notice Function to invest funds into SushiSwap WBTC/ETH pool, deposit SLP token into Pickle Jar(vault contract)
/// @notice and stake Pickle LP token into Pickle Farm(staking contract)
/// @param _amount Amount to invest in ETH
function _investWBTCETH(uint256 _amount) private {
uint256 _amountIn = _amount.div(2);
uint256[] memory _amounts = _swapExactTokensForTokens(address(WETH), address(WBTC), _amountIn);
if (_amounts[1] > 0) {
(uint256 _amountA, uint256 _amountB, uint256 _slpWBTC) = router.addLiquidity(
address(WBTC), address(WETH),
_amounts[1], _amountIn,
0, 0,
address(this), block.timestamp
);
emit AddLiquidity(address(slpWBTC), _amountA, _amountB, _slpWBTC);
pickleJarWBTC.deposit(_slpWBTC);
gaugeP_WBTC.deposit(pickleJarWBTC.balanceOf(address(this)));
_poolWBTCETH = _poolWBTCETH.add(_amount);
}
}
/// @notice Function to invest funds into SushiSwap DPI/ETH pool
/// @notice and stake SLP token into SushiSwap MasterChef(staking contract)
/// @param _amount Amount to invest in ETH
function _investDPIETH(uint256 _amount) private {
uint256 _amountIn = _amount.div(2);
uint256[] memory _amounts = _swapExactTokensForTokens(address(WETH), address(DPI), _amountIn);
if (_amounts[1] > 0) {
(uint256 _amountA, uint256 _amountB, uint256 _slpDPI) = router.addLiquidity(address(DPI), address(WETH), _amounts[1], _amountIn, 0, 0, address(this), block.timestamp);
masterChef.deposit(42, _slpDPI);
_poolDPIETH = _poolDPIETH.add(_amount);
emit AddLiquidity(address(slpDPI), _amountA, _amountB, _slpDPI);
}
}
/// @notice Function to invest funds into SushiSwap DAI/ETH pool, deposit SLP token into Pickle Jar(vault contract)
/// @notice and stake Pickle LP token into Pickle Farm(staking contract)
/// @param _amount Amount to invest in ETH
function _investDAIETH(uint256 _amount) private {
uint256 _amountIn = _amount.div(2);
uint256[] memory _amounts = _swapExactTokensForTokens(address(WETH), address(DAI), _amountIn);
if (_amounts[1] > 0) {
(uint256 _amountA, uint256 _amountB, uint256 _slpDAI) = router.addLiquidity(
address(DAI), address(WETH),
_amounts[1], _amountIn,
0, 0,
address(this), block.timestamp
);
emit AddLiquidity(address(slpDAI), _amountA, _amountB, _slpDAI); // 1389.083912192186144530 0.335765206816332767 17.202418926243352766
pickleJarDAI.deposit(_slpDAI);
gaugeP_DAI.deposit(pickleJarDAI.balanceOf(address(this)));
_poolDAIETH = _poolDAIETH.add(_amount);
}
}
// @notice Function to reimburse vault minimum keep amount by removing liquidity from all farms
function reimburse() external onlyVault {
// Get total reimburse amount (6 decimals)
uint256 _reimburseUSDT = vault.getReimburseTokenAmount(0);
uint256 _reimburseUSDC = vault.getReimburseTokenAmount(1);
uint256 _reimburseDAI = vault.getReimburseTokenAmount(2);
uint256 _totalReimburse = _reimburseUSDT.add(_reimburseUSDC).add(_reimburseDAI.div(1e12));
// Get ETH needed from farm (by removing liquidity then swap to ETH)
uint256[] memory _amounts = router.getAmountsOut(_totalReimburse, _getPath(address(USDT), address(WETH)));
if (WETH.balanceOf(address(this)) < _amounts[1]) { // Balance of WETH > _amounts[1] when execute emergencyWithdraw()
_updatePoolForPriceChange();
uint256 _thirtyPercOfAmtWithdraw = _amounts[1].mul(3000).div(DENOMINATOR);
_withdrawCurve(_thirtyPercOfAmtWithdraw); // 30% from Curve HBTC/WBTC
_withdrawPickleWBTC(_thirtyPercOfAmtWithdraw); // 30% from Pickle WBTC/ETH
_withdrawSushiswap(_thirtyPercOfAmtWithdraw); // 30% from SushiSwap DPI/ETH
_withdrawPickleDAI(_amounts[1].sub(_thirtyPercOfAmtWithdraw).sub(_thirtyPercOfAmtWithdraw).sub(_thirtyPercOfAmtWithdraw)); // 10% from Pickle DAI/ETH
_swapAllToETH(); // Swap WBTC, DPI & DAI that get from withdrawal above to WETH
}
// Swap WETH to token and transfer back to vault
uint256 _WETHBalance = WETH.balanceOf(address(this));
_reimburse(_WETHBalance.mul(_reimburseUSDT).div(_totalReimburse), USDT);
_reimburse(_WETHBalance.mul(_reimburseUSDC).div(_totalReimburse), USDC);
_reimburse((WETH.balanceOf(address(this))), DAI);
}
/// @notice reimburse() nested function
/// @param _reimburseAmt Amount to reimburse in ETH
/// @param _token Type of token to reimburse
function _reimburse(uint256 _reimburseAmt, IERC20 _token) private {
if (_reimburseAmt > 0) {
uint256[] memory _amounts = _swapExactTokensForTokens(address(WETH), address(_token), _reimburseAmt);
_token.safeTransfer(address(vault), _amounts[1]);
}
}
/// @notice Function to withdraw all funds from all farms
function emergencyWithdraw() external onlyVault {
// 1. Withdraw all token from all farms
// Since to withdraw all funds, there is no need to _updatePoolForPriceChange()
// Curve HBTC/WBTC
mintr.mint(address(gaugeC));
_withdrawCurve(_poolHBTCWBTC);
// Pickle WBTC/ETH
gaugeP_WBTC.getReward();
_withdrawPickleWBTC(_poolWBTCETH);
// Sushiswap DPI/ETH
_withdrawSushiswap(_poolDPIETH);
// Pickle DAI/ETH
gaugeP_WBTC.getReward();
_withdrawPickleDAI(_poolDAIETH);
// 2.1 Swap all rewards to WETH
uint256 balanceOfWETHBefore = WETH.balanceOf(address(this));
_swapExactTokensForTokens(address(CRV), address(WETH), CRV.balanceOf(address(this)));
_swapExactTokensForTokens(address(PICKLE), address(WETH), PICKLE.balanceOf(address(this)));
_swapExactTokensForTokens(address(SUSHI), address(WETH), SUSHI.balanceOf(address(this)));
// Send portion rewards to admin
uint256 _rewards = (WETH.balanceOf(address(this))).sub(balanceOfWETHBefore);
uint256 _adminFees = _rewards.mul(yieldFeePerc).div(DENOMINATOR);
_splitYieldFees(_adminFees);
// 2.2 Swap WBTC, DPI & DAI to WETH
_swapAllToETH();
_pool = WETH.balanceOf(address(this));
isVesting = true;
}
/// @notice Function to invest back WETH into farms after emergencyWithdraw()
function reinvest() external onlyVault {
_pool = 0;
isVesting = false;
_updatePoolForProvideLiquidity();
}
/// @notice Function to swap tokens with SushiSwap
/// @param _tokenA Token to be swapped
/// @param _tokenB Token to be received
/// @param _amountIn Amount of token to be swapped
/// @return _amounts Array that contains swapped amounts
function _swapExactTokensForTokens(address _tokenA, address _tokenB, uint256 _amountIn) private returns (uint256[] memory _amounts) {
address[] memory _path = _getPath(_tokenA, _tokenB);
uint256[] memory _amountsOut = router.getAmountsOut(_amountIn, _path);
if (_amountsOut[1] > 0) {
_amounts = router.swapExactTokensForTokens(_amountIn, 0, _path, address(this), block.timestamp);
} else {
// Not enough amount to swap
uint256[] memory _zeroReturn = new uint256[](2);
_zeroReturn[0] = 0;
_zeroReturn[1] = 0;
return _zeroReturn;
}
}
/// @notice Function to withdraw funds from farms if withdraw amount > amount keep in vault
/// @param _amount Amount to withdraw in ETH
function withdraw(uint256 _amount) external onlyVault {
if (!isVesting) {
// Update to latest pool
_updatePoolForPriceChange();
uint256 _totalPool = _getTotalPool();
// _WETHAmtBefore: Need this because there will be leftover after provide liquidity to farms
uint256 _WETHAmtBefore = WETH.balanceOf(address(this));
// Withdraw from Curve HBTC/WBTC
_withdrawCurve(_poolHBTCWBTC.mul(_amount).div(_totalPool));
// Withdraw from Pickle WBTC/ETH
_withdrawPickleWBTC(_poolWBTCETH.mul(_amount).div(_totalPool));
// Withdraw from Sushiswap DPI/ETH
_withdrawSushiswap(_poolDPIETH.mul(_amount).div(_totalPool));
// Withdraw from Pickle DAI/ETH
_withdrawPickleDAI(_poolDAIETH.mul(_amount).div(_totalPool));
_swapAllToETH(); // Swap WBTC, DPI & DAI that get from withdrawal above to WETH
WETH.safeTransfer(msg.sender, (WETH.balanceOf(address(this))).sub(_WETHAmtBefore));
} else {
_pool = _pool.sub(_amount);
WETH.safeTransfer(msg.sender, _amount);
}
}
/// @notice Function to unstake LP token(gaugeC) and remove liquidity(cPairs) from Curve
/// @param _amount Amount to withdraw in ETH
function _withdrawCurve(uint256 _amount) private {
uint256 _totalClpToken = gaugeC.balanceOf(address(this));
uint256 _clpTokenShare = _totalClpToken.mul(_amount).div(_poolHBTCWBTC);
gaugeC.withdraw(_clpTokenShare);
cPairs.remove_liquidity_one_coin(_clpTokenShare, 1, 0);
_poolHBTCWBTC = _poolHBTCWBTC.sub(_amount);
}
/// @notice Function to unstake LP token from Pickle Farm(gaugeP_WBTC),
/// @notice withdraw from Pickle Jar(pickleJarWBTC),
/// @notice and remove liquidity(router) from SushiSwap
/// @param _amount Amount to withdraw in ETH
function _withdrawPickleWBTC(uint256 _amount) private {
uint256 _totalPlpToken = gaugeP_WBTC.balanceOf(address(this));
uint256 _plpTokenShare = _totalPlpToken.mul(_amount).div(_poolWBTCETH);
gaugeP_WBTC.withdraw(_plpTokenShare);
pickleJarWBTC.withdraw(_plpTokenShare);
router.removeLiquidity(address(WBTC), address(WETH), slpWBTC.balanceOf(address(this)), 0, 0, address(this), block.timestamp);
_poolWBTCETH = _poolWBTCETH.sub(_amount);
}
/// @notice Function to unstake LP token(masterChef) and remove liquidity(router) from SushiSwap
/// @param _amount Amount to withdraw in ETH
function _withdrawSushiswap(uint256 _amount) private {
(uint256 _totalSlpToken,) = masterChef.userInfo(42, address(this));
uint256 _slpTokenShare = _totalSlpToken.mul(_amount).div(_poolDPIETH);
masterChef.withdraw(42, _slpTokenShare);
router.removeLiquidity(address(DPI), address(WETH), _slpTokenShare, 0, 0, address(this), block.timestamp);
_poolDPIETH = _poolDPIETH.sub(_amount);
}
/// @notice Function to unstake LP token from Pickle Farm(gaugeP_DAI),
/// @notice withdraw from Pickle Jar(pickleJarDAI),
/// @notice and remove liquidity(router) from SushiSwap
/// @param _amount Amount to withdraw in ETH
function _withdrawPickleDAI(uint256 _amount) private {
uint256 _totalPlpToken = gaugeP_DAI.balanceOf(address(this));
uint256 _plpTokenShare = _totalPlpToken.mul(_amount).div(_poolDAIETH);
gaugeP_DAI.withdraw(_plpTokenShare);
pickleJarDAI.withdraw(_plpTokenShare);
router.removeLiquidity(address(DAI), address(WETH), slpDAI.balanceOf(address(this)), 0, 0, address(this), block.timestamp);
_poolDAIETH = _poolDAIETH.sub(_amount);
}
/// @notice Function to swap tokens that receive by removing liquidity for all farms
function _swapAllToETH() private {
_swapExactTokensForTokens(address(WBTC), address(WETH), WBTC.balanceOf(address(this)));
_swapExactTokensForTokens(address(DPI), address(WETH), DPI.balanceOf(address(this)));
_swapExactTokensForTokens(address(DAI), address(WETH), DAI.balanceOf(address(this)));
}
/// @notice Function to set new admin address from vault contract
/// @param _admin Address of new admin
function setAdmin(address _admin) external onlyVault {
admin = _admin;
}
/// @notice Function to set new strategist address from vault contract
/// @param _strategist Address of new strategist
function setStrategist(address _strategist) external onlyVault {
strategist = _strategist;
}
/// @notice Function to approve vault to migrate funds from this contract to new strategy contract
function approveMigrate() external onlyOwner {
require(isVesting, "Not in vesting state");
if (WETH.allowance(address(this), address(vault)) == 0) {
WETH.safeApprove(address(vault), type(uint256).max);
}
}
/// @notice Function to get path for SushiSwap swap functions
/// @param _tokenA Token to be swapped
/// @param _tokenB Token to be received
/// @return _path Array of address
function _getPath(address _tokenA, address _tokenB) private pure returns (address[] memory) {
address[] memory _path = new address[](2);
_path[0] = _tokenA;
_path[1] = _tokenB;
return _path;
}
/// @notice Function to get latest LP token price for all farms
/// @return All LP token price in ETH
function _getLPTokenPrice() private view returns (uint256, uint256, uint256, uint256) {
// 1. Get tokens price in ETH
uint256 _wbtcPrice = (router.getAmountsOut(1e8, _getPath(address(WBTC), address(WETH))))[1];
uint256 _dpiPrice = _getTokenPriceFromChainlink(0x029849bbc0b1d93b85a8b6190e979fd38F5760E2); // DPI/ETH
uint256 _daiPrice = _getTokenPriceFromChainlink(0x773616E4d11A78F511299002da57A0a94577F1f4); // DAI/ETH
// 2. Calculate LP token price
// Curve HBTC/WBTC
uint256 _amountACurve = cPairs.balances(0); // HBTC, 18 decimals
uint256 _amountBCurve = (cPairs.balances(1)).mul(1e10); // WBTC, 8 decimals to 18 decimals
uint256 _totalValueOfHBTCWBTC = _calcTotalValueOfLiquidityPool(_amountACurve, _wbtcPrice, _amountBCurve, _wbtcPrice);
uint256 _clpTokenPriceHBTC = _calcValueOf1LPToken(_totalValueOfHBTCWBTC, clpToken.totalSupply());
// Pickle WBTC/ETH
uint256 _pSlpTokenPriceWBTC = _calcPslpTokenPrice(pickleJarWBTC, slpWBTC, _wbtcPrice);
// Sushiswap DPI/ETH
uint256 _slpTokenPriceDPI = _calcSlpTokenPrice(slpDPI, _dpiPrice);
// Pickle DAI/ETH
uint256 _pSlpTokenPriceDAI = _calcPslpTokenPrice(pickleJarDAI, slpDAI, _daiPrice);
return (_clpTokenPriceHBTC, _pSlpTokenPriceWBTC, _slpTokenPriceDPI, _pSlpTokenPriceDAI);
}
/// @notice Function to calculate price of Pickle LP token
/// @param _pslpToken Type of Pickle SLP token
/// @param _slpToken Type of SushiSwap LP token
/// @param _tokenAPrice Price of SushiSwap LP token
/// @return Price of Pickle LP token in ETH
function _calcPslpTokenPrice(IPickleJar _pslpToken, ISLPToken _slpToken, uint256 _tokenAPrice) private view returns (uint256) {
uint256 _slpTokenPrice = _calcSlpTokenPrice(_slpToken, _tokenAPrice);
uint256 _totalValueOfPSlpToken = _calcTotalValueOfLiquidityPool(_pslpToken.balance(), _slpTokenPrice, 0, 0);
return _calcValueOf1LPToken(_totalValueOfPSlpToken, _pslpToken.totalSupply());
}
/// @notice Function to calculate price of SushiSwap LP Token
/// @param _slpToken Type of SushiSwap LP token
/// @param _tokenAPrice Price of SushiSwap LP token
/// @return Price of SushiSwap LP Token in ETH
function _calcSlpTokenPrice(ISLPToken _slpToken, uint256 _tokenAPrice) private view returns (uint256) {
(uint112 _reserveA, uint112 _reserveB,) = _slpToken.getReserves();
if (_slpToken == slpWBTC) { // Change WBTC to 18 decimals
_reserveA * 1e10;
}
uint256 _totalValueOfLiquidityPool = _calcTotalValueOfLiquidityPool(uint256(_reserveA), _tokenAPrice, uint256(_reserveB), 1e18);
return _calcValueOf1LPToken(_totalValueOfLiquidityPool, _slpToken.totalSupply());
}
/// @notice Calculate total value of liquidity pool
/// @param _amountA Amount of one side of reserves
/// @param _priceA Price of one side of reserves
/// @param _amountB Amount of another side of reserves (if available)
/// @param _priceB Price of another side of reserves (if available)
/// @return Total value of liquidity pool (18 decimals)
function _calcTotalValueOfLiquidityPool(uint256 _amountA, uint256 _priceA, uint256 _amountB, uint256 _priceB) private pure returns (uint256) {
return (_amountA.mul(_priceA)).add(_amountB.mul(_priceB));
}
/// @notice Function to calculate price of 1 LP Token
/// @param _totalValueOfLiquidityPool Amount from _calcTotalValueOfLiquidityPool()
/// @param _circulatingSupplyOfLPTokens totalSupply() of LP token
/// @return Price of 1 LP Token (18 decimals)
function _calcValueOf1LPToken(uint256 _totalValueOfLiquidityPool, uint256 _circulatingSupplyOfLPTokens) private pure returns (uint256) {
return _totalValueOfLiquidityPool.div(_circulatingSupplyOfLPTokens);
}
/// @notice Function to get token price(only for DPI and DAI in this contract)
/// @param _priceFeedProxy Address of ChainLink contract that provide oracle price
/// @return Price in ETH
function _getTokenPriceFromChainlink(address _priceFeedProxy) private view returns (uint256) {
IChainlink _pricefeed = IChainlink(_priceFeedProxy);
int256 _price = _pricefeed.latestAnswer();
return uint256(_price);
}
/// @notice Get current pool(sum of 4 pools with latest price updated)
/// @return Current pool in ETH
function getCurrentPool() public view returns (uint256) {
if (!isVesting) {
(uint256 _clpTokenPriceHBTC, uint256 _pSlpTokenPriceWBTC, uint256 _slpTokenPriceDPI, uint256 _pSlpTokenPriceDAI) = _getLPTokenPrice();
uint256 poolHBTCWBTC = _poolHBTCWBTC.mul(_clpTokenPriceHBTC).div(_HBTCWBTCLPTokenPrice);
uint256 poolWBTCETH = _poolWBTCETH.mul(_pSlpTokenPriceWBTC).div(_WBTCETHLPTokenPrice);
uint256 poolDPIETH = _poolDPIETH.mul(_slpTokenPriceDPI).div(_DPIETHLPTokenPrice);
uint256 poolDAIETH = _poolDAIETH.mul(_pSlpTokenPriceDAI).div(_DAIETHLPTokenPrice);
return poolHBTCWBTC.add(poolWBTCETH).add(poolDPIETH).add(poolDAIETH);
} else {
return _pool;
}
}
/// @notice Get total pool(sum of 4 pools)
/// @return Total pool in ETH
function _getTotalPool() private view returns (uint256) {
if (!isVesting) {
return _poolHBTCWBTC.add(_poolWBTCETH).add(_poolDPIETH).add(_poolDAIETH);
} else {
return _pool;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
|
Function to set new admin address from vault contract _admin Address of new admin
|
function setAdmin(address _admin) external onlyVault {
admin = _admin;
}
| 13,496,279 |
// SPDX-License-Identifier: MIT
// solhint-disable
/*
This is copied from OZ preset: https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/release-v3.0.0/contracts/presets/ERC721PresetMinterPauserAutoId.sol
Alterations:
* Make the counter public, so that we can use it in our custom mint function
* Removed ERC721Burnable parent contract, but added our own custom burn function.
* Removed original "mint" function, because we have a custom one.
* Removed default initialization functions, because they set msg.sender as the owner, which
we do not want, because we use a deployer account, which is separate from the protocol owner.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Counters.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721Pausable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol";
/**
* @dev {ERC721} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
* - token ID and URI autogeneration
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to aother accounts
*/
contract ERC721PresetMinterPauserAutoIdUpgradeSafe is
Initializable,
ContextUpgradeSafe,
AccessControlUpgradeSafe,
ERC721PausableUpgradeSafe
{
using Counters for Counters.Counter;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
Counters.Counter public _tokenIdTracker;
/**
* @dev Pauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721PausableUpgradeSafe) {
super._beforeTokenTransfer(from, to, tokenId);
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
import "../Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, _msgSender()));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*/
abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
import "../Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
pragma solidity ^0.6.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC721.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./IERC721Receiver.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../utils/EnumerableSet.sol";
import "../../utils/EnumerableMap.sol";
import "../../utils/Strings.sol";
import "../../Initializable.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721UpgradeSafe is Initializable, ContextUpgradeSafe, ERC165UpgradeSafe, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
function __ERC721_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name, symbol);
}
function __ERC721_init_unchained(string memory name, string memory symbol) internal initializer {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev Gets the balance of the specified address.
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If a base URI is set (via {_setBaseURI}), it is added as a prefix to the
* token's own URI (via {_setTokenURI}).
*
* If there is a base URI but no token URI, the token's ID will be used as
* its URI when appending it to the base URI. This pattern for autogenerated
* token URIs can lead to large gas savings.
*
* .Examples
* |===
* |`_setBaseURI()` |`_setTokenURI()` |`tokenURI()`
* | ""
* | ""
* | ""
* | ""
* | "token.uri/123"
* | "token.uri/123"
* | "token.uri/"
* | "123"
* | "token.uri/123"
* | "token.uri/"
* | ""
* | "token.uri/<tokenId>"
* |===
*
* Requirements:
*
* - `tokenId` must exist.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// If there is no base URI, return the token URI.
if (bytes(_baseURI).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(_baseURI, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view returns (string memory) {
return _baseURI;
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens.
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param operator operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner.
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the _msgSender() to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to set the token URI for a given token.
*
* Reverts if the token ID does not exist.
*
* TIP: If all token IDs share a prefix (for example, if your URIs look like
* `https://api.myproject.com/token/<id>`), use {_setBaseURI} to store
* it and save gas.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = to.call(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
));
if (!success) {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert("ERC721: transfer to non ERC721Receiver implementer");
}
} else {
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - when `from` is zero, `tokenId` will be minted for `to`.
* - when `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
uint256[41] private __gap;
}
pragma solidity ^0.6.0;
import "./ERC721.sol";
import "../../utils/Pausable.sol";
import "../../Initializable.sol";
/**
* @dev ERC721 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC721PausableUpgradeSafe is Initializable, ERC721UpgradeSafe, PausableUpgradeSafe {
function __ERC721Pausable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__Pausable_init_unchained();
__ERC721Pausable_init_unchained();
}
function __ERC721Pausable_init_unchained() internal initializer {
}
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
require(!paused(), "ERC721Pausable: token transfer while paused");
}
uint256[50] private __gap;
}
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.2;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
pragma solidity ^0.6.2;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
pragma solidity ^0.6.2;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
function totalSupply() external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
function tokenByIndex(uint256 index) external view returns (uint256);
}
pragma solidity ^0.6.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
external returns (bytes4);
}
pragma solidity ^0.6.0;
import "./IERC165.sol";
import "../Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165UpgradeSafe is Initializable, IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
pragma solidity ^0.6.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
import "../Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/drafts/IERC20Permit.sol";
import "../external/ERC721PresetMinterPauserAutoId.sol";
import "../interfaces/IERC20withDec.sol";
import "../interfaces/ISeniorPool.sol";
import "../protocol/core/GoldfinchConfig.sol";
import "../protocol/core/ConfigHelper.sol";
import "../protocol/core/BaseUpgradeablePausable.sol";
import "../library/StakingRewardsVesting.sol";
contract StakingRewards is ERC721PresetMinterPauserAutoIdUpgradeSafe, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20withDec;
using ConfigHelper for GoldfinchConfig;
using StakingRewardsVesting for StakingRewardsVesting.Rewards;
enum LockupPeriod {
SixMonths,
TwelveMonths,
TwentyFourMonths
}
struct StakedPosition {
// @notice Staked amount denominated in `stakingToken().decimals()`
uint256 amount;
// @notice Struct describing rewards owed with vesting
StakingRewardsVesting.Rewards rewards;
// @notice Multiplier applied to staked amount when locking up position
uint256 leverageMultiplier;
// @notice Time in seconds after which position can be unstaked
uint256 lockedUntil;
}
/* ========== EVENTS =================== */
event RewardsParametersUpdated(
address indexed who,
uint256 targetCapacity,
uint256 minRate,
uint256 maxRate,
uint256 minRateAtPercent,
uint256 maxRateAtPercent
);
event TargetCapacityUpdated(address indexed who, uint256 targetCapacity);
event VestingScheduleUpdated(address indexed who, uint256 vestingLength);
event MinRateUpdated(address indexed who, uint256 minRate);
event MaxRateUpdated(address indexed who, uint256 maxRate);
event MinRateAtPercentUpdated(address indexed who, uint256 minRateAtPercent);
event MaxRateAtPercentUpdated(address indexed who, uint256 maxRateAtPercent);
event LeverageMultiplierUpdated(address indexed who, LockupPeriod lockupPeriod, uint256 leverageMultiplier);
/* ========== STATE VARIABLES ========== */
uint256 private constant MULTIPLIER_DECIMALS = 1e18;
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
GoldfinchConfig public config;
/// @notice The block timestamp when rewards were last checkpointed
uint256 public lastUpdateTime;
/// @notice Accumulated rewards per token at the last checkpoint
uint256 public accumulatedRewardsPerToken;
/// @notice Total rewards available for disbursement at the last checkpoint, denominated in `rewardsToken()`
uint256 public rewardsAvailable;
/// @notice StakedPosition tokenId => accumulatedRewardsPerToken at the position's last checkpoint
mapping(uint256 => uint256) public positionToAccumulatedRewardsPerToken;
/// @notice Desired supply of staked tokens. The reward rate adjusts in a range
/// around this value to incentivize staking or unstaking to maintain it.
uint256 public targetCapacity;
/// @notice The minimum total disbursed rewards per second, denominated in `rewardsToken()`
uint256 public minRate;
/// @notice The maximum total disbursed rewards per second, denominated in `rewardsToken()`
uint256 public maxRate;
/// @notice The percent of `targetCapacity` at which the reward rate reaches `maxRate`.
/// Represented with `MULTIPLIER_DECIMALS`.
uint256 public maxRateAtPercent;
/// @notice The percent of `targetCapacity` at which the reward rate reaches `minRate`.
/// Represented with `MULTIPLIER_DECIMALS`.
uint256 public minRateAtPercent;
/// @notice The duration in seconds over which rewards vest
uint256 public vestingLength;
/// @dev Supply of staked tokens, excluding leverage due to lock-up boosting, denominated in
/// `stakingToken().decimals()`
uint256 public totalStakedSupply;
/// @dev Supply of staked tokens, including leverage due to lock-up boosting, denominated in
/// `stakingToken().decimals()`
uint256 private totalLeveragedStakedSupply;
/// @dev A mapping from lockup periods to leverage multipliers used to boost rewards.
/// See `stakeWithLockup`.
mapping(LockupPeriod => uint256) private leverageMultipliers;
/// @dev NFT tokenId => staked position
mapping(uint256 => StakedPosition) public positions;
// solhint-disable-next-line func-name-mixedcase
function __initialize__(address owner, GoldfinchConfig _config) external initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained("Goldfinch V2 LP Staking Tokens", "GFI-V2-LPS");
__ERC721Pausable_init_unchained();
__AccessControl_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
_setupRole(OWNER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
config = _config;
vestingLength = 365 days;
// Set defaults for leverage multipliers (no boosting)
leverageMultipliers[LockupPeriod.SixMonths] = MULTIPLIER_DECIMALS; // 1x
leverageMultipliers[LockupPeriod.TwelveMonths] = MULTIPLIER_DECIMALS; // 1x
leverageMultipliers[LockupPeriod.TwentyFourMonths] = MULTIPLIER_DECIMALS; // 1x
}
/* ========== VIEWS ========== */
/// @notice Returns the staked balance of a given position token
/// @param tokenId A staking position token ID
/// @return Amount of staked tokens denominated in `stakingToken().decimals()`
function stakedBalanceOf(uint256 tokenId) external view returns (uint256) {
return positions[tokenId].amount;
}
/// @notice The address of the token being disbursed as rewards
function rewardsToken() public view returns (IERC20withDec) {
return config.getGFI();
}
/// @notice The address of the token that can be staked
function stakingToken() public view returns (IERC20withDec) {
return config.getFidu();
}
/// @notice The additional rewards earned per token, between the provided time and the last
/// time rewards were checkpointed, given the prevailing `rewardRate()`. This amount is limited
/// by the amount of rewards that are available for distribution; if there aren't enough
/// rewards in the balance of this contract, then we shouldn't be giving them out.
/// @return Amount of rewards denominated in `rewardsToken().decimals()`.
function additionalRewardsPerTokenSinceLastUpdate(uint256 time) internal view returns (uint256) {
require(time >= lastUpdateTime, "Invalid end time for range");
if (totalLeveragedStakedSupply == 0) {
return 0;
}
uint256 rewardsSinceLastUpdate = Math.min(time.sub(lastUpdateTime).mul(rewardRate()), rewardsAvailable);
uint256 additionalRewardsPerToken = rewardsSinceLastUpdate.mul(stakingTokenMantissa()).div(
totalLeveragedStakedSupply
);
// Prevent perverse, infinite-mint scenario where totalLeveragedStakedSupply is a fraction of a token.
// Since it's used as the denominator, this could make additionalRewardPerToken larger than the total number
// of tokens that should have been disbursed in the elapsed time. The attacker would need to find
// a way to reduce totalLeveragedStakedSupply while maintaining a staked position of >= 1.
// See: https://twitter.com/Mudit__Gupta/status/1409463917290557440
if (additionalRewardsPerToken > rewardsSinceLastUpdate) {
return 0;
}
return additionalRewardsPerToken;
}
/// @notice Returns accumulated rewards per token up to the current block timestamp
/// @return Amount of rewards denominated in `rewardsToken().decimals()`
function rewardPerToken() public view returns (uint256) {
uint256 additionalRewardsPerToken = additionalRewardsPerTokenSinceLastUpdate(block.timestamp);
return accumulatedRewardsPerToken.add(additionalRewardsPerToken);
}
/// @notice Returns rewards earned by a given position token from its last checkpoint up to the
/// current block timestamp.
/// @param tokenId A staking position token ID
/// @return Amount of rewards denominated in `rewardsToken().decimals()`
function earnedSinceLastCheckpoint(uint256 tokenId) public view returns (uint256) {
StakedPosition storage position = positions[tokenId];
uint256 leveredAmount = positionToLeveredAmount(position);
return
leveredAmount.mul(rewardPerToken().sub(positionToAccumulatedRewardsPerToken[tokenId])).div(
stakingTokenMantissa()
);
}
/// @notice Returns the rewards claimable by a given position token at the most recent checkpoint, taking into
/// account vesting schedule.
/// @return rewards Amount of rewards denominated in `rewardsToken()`
function claimableRewards(uint256 tokenId) public view returns (uint256 rewards) {
return positions[tokenId].rewards.claimable();
}
/// @notice Returns the rewards that will have vested for some position with the given params.
/// @return rewards Amount of rewards denominated in `rewardsToken()`
function totalVestedAt(
uint256 start,
uint256 end,
uint256 time,
uint256 grantedAmount
) external pure returns (uint256 rewards) {
return StakingRewardsVesting.totalVestedAt(start, end, time, grantedAmount);
}
/// @notice Number of rewards, in `rewardsToken().decimals()`, to disburse each second
function rewardRate() internal view returns (uint256) {
// The reward rate can be thought of as a piece-wise function:
//
// let intervalStart = (maxRateAtPercent * targetCapacity),
// intervalEnd = (minRateAtPercent * targetCapacity),
// x = totalStakedSupply
// in
// if x < intervalStart
// y = maxRate
// if x > intervalEnd
// y = minRate
// else
// y = maxRate - (maxRate - minRate) * (x - intervalStart) / (intervalEnd - intervalStart)
//
// See an example here:
// solhint-disable-next-line max-line-length
// https://www.wolframalpha.com/input/?i=Piecewise%5B%7B%7B1000%2C+x+%3C+50%7D%2C+%7B100%2C+x+%3E+300%7D%2C+%7B1000+-+%281000+-+100%29+*+%28x+-+50%29+%2F+%28300+-+50%29+%2C+50+%3C+x+%3C+300%7D%7D%5D
//
// In that example:
// maxRateAtPercent = 0.5, minRateAtPercent = 3, targetCapacity = 100, maxRate = 1000, minRate = 100
uint256 intervalStart = targetCapacity.mul(maxRateAtPercent).div(MULTIPLIER_DECIMALS);
uint256 intervalEnd = targetCapacity.mul(minRateAtPercent).div(MULTIPLIER_DECIMALS);
uint256 x = totalStakedSupply;
// Subsequent computation would overflow
if (intervalEnd <= intervalStart) {
return 0;
}
if (x < intervalStart) {
return maxRate;
}
if (x > intervalEnd) {
return minRate;
}
return maxRate.sub(maxRate.sub(minRate).mul(x.sub(intervalStart)).div(intervalEnd.sub(intervalStart)));
}
function positionToLeveredAmount(StakedPosition storage position) internal view returns (uint256) {
return toLeveredAmount(position.amount, position.leverageMultiplier);
}
function toLeveredAmount(uint256 amount, uint256 leverageMultiplier) internal pure returns (uint256) {
return amount.mul(leverageMultiplier).div(MULTIPLIER_DECIMALS);
}
function stakingTokenMantissa() internal view returns (uint256) {
return uint256(10)**stakingToken().decimals();
}
/// @notice The amount of rewards currently being earned per token per second. This amount takes into
/// account how many rewards are actually available for disbursal -- unlike `rewardRate()` which does not.
/// This function is intended for public consumption, to know the rate at which rewards are being
/// earned, and not as an input to the mutative calculations in this contract.
/// @return Amount of rewards denominated in `rewardsToken().decimals()`.
function currentEarnRatePerToken() public view returns (uint256) {
uint256 time = block.timestamp == lastUpdateTime ? block.timestamp + 1 : block.timestamp;
uint256 elapsed = time.sub(lastUpdateTime);
return additionalRewardsPerTokenSinceLastUpdate(time).div(elapsed);
}
/// @notice The amount of rewards currently being earned per second, for a given position. This function
/// is intended for public consumption, to know the rate at which rewards are being earned
/// for a given position, and not as an input to the mutative calculations in this contract.
/// @return Amount of rewards denominated in `rewardsToken().decimals()`.
function positionCurrentEarnRate(uint256 tokenId) external view returns (uint256) {
StakedPosition storage position = positions[tokenId];
uint256 leveredAmount = positionToLeveredAmount(position);
return currentEarnRatePerToken().mul(leveredAmount).div(stakingTokenMantissa());
}
/* ========== MUTATIVE FUNCTIONS ========== */
/// @notice Stake `stakingToken()` to earn rewards. When you call this function, you'll receive an
/// an NFT representing your staked position. You can present your NFT to `getReward` or `unstake`
/// to claim rewards or unstake your tokens respectively. Rewards vest over a schedule.
/// @dev This function checkpoints rewards.
/// @param amount The amount of `stakingToken()` to stake
function stake(uint256 amount) external nonReentrant whenNotPaused updateReward(0) {
_stakeWithLockup(msg.sender, msg.sender, amount, 0, MULTIPLIER_DECIMALS);
}
/// @notice Stake `stakingToken()` and lock your position for a period of time to boost your rewards.
/// When you call this function, you'll receive an an NFT representing your staked position.
/// You can present your NFT to `getReward` or `unstake` to claim rewards or unstake your tokens
/// respectively. Rewards vest over a schedule.
///
/// A locked position's rewards are boosted using a multiplier on the staked balance. For example,
/// if I lock 100 tokens for a 2x multiplier, my rewards will be calculated as if I staked 200 tokens.
/// This mechanism is similar to curve.fi's CRV-boosting vote-locking. Locked positions cannot be
/// unstaked until after the position's lockedUntil timestamp.
/// @dev This function checkpoints rewards.
/// @param amount The amount of `stakingToken()` to stake
/// @param lockupPeriod The period over which to lock staked tokens
function stakeWithLockup(uint256 amount, LockupPeriod lockupPeriod)
external
nonReentrant
whenNotPaused
updateReward(0)
{
uint256 lockDuration = lockupPeriodToDuration(lockupPeriod);
uint256 leverageMultiplier = getLeverageMultiplier(lockupPeriod);
uint256 lockedUntil = block.timestamp.add(lockDuration);
_stakeWithLockup(msg.sender, msg.sender, amount, lockedUntil, leverageMultiplier);
}
/// @notice Deposit to SeniorPool and stake your shares in the same transaction.
/// @param usdcAmount The amount of USDC to deposit into the senior pool. All shares from deposit
/// will be staked.
function depositAndStake(uint256 usdcAmount) public nonReentrant whenNotPaused updateReward(0) {
uint256 fiduAmount = depositToSeniorPool(usdcAmount);
uint256 lockedUntil = 0;
uint256 tokenId = _stakeWithLockup(address(this), msg.sender, fiduAmount, lockedUntil, MULTIPLIER_DECIMALS);
emit DepositedAndStaked(msg.sender, usdcAmount, tokenId, fiduAmount, lockedUntil, MULTIPLIER_DECIMALS);
}
function depositToSeniorPool(uint256 usdcAmount) internal returns (uint256 fiduAmount) {
require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed");
IERC20withDec usdc = config.getUSDC();
usdc.safeTransferFrom(msg.sender, address(this), usdcAmount);
ISeniorPool seniorPool = config.getSeniorPool();
usdc.safeIncreaseAllowance(address(seniorPool), usdcAmount);
return seniorPool.deposit(usdcAmount);
}
/// @notice Identical to `depositAndStake`, except it allows for a signature to be passed that permits
/// this contract to move funds on behalf of the user.
/// @param usdcAmount The amount of USDC to deposit
/// @param v secp256k1 signature component
/// @param r secp256k1 signature component
/// @param s secp256k1 signature component
function depositWithPermitAndStake(
uint256 usdcAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), usdcAmount, deadline, v, r, s);
depositAndStake(usdcAmount);
}
/// @notice Deposit to the `SeniorPool` and stake your shares with a lock-up in the same transaction.
/// @param usdcAmount The amount of USDC to deposit into the senior pool. All shares from deposit
/// will be staked.
/// @param lockupPeriod The period over which to lock staked tokens
function depositAndStakeWithLockup(uint256 usdcAmount, LockupPeriod lockupPeriod)
public
nonReentrant
whenNotPaused
updateReward(0)
{
uint256 fiduAmount = depositToSeniorPool(usdcAmount);
uint256 lockDuration = lockupPeriodToDuration(lockupPeriod);
uint256 leverageMultiplier = getLeverageMultiplier(lockupPeriod);
uint256 lockedUntil = block.timestamp.add(lockDuration);
uint256 tokenId = _stakeWithLockup(address(this), msg.sender, fiduAmount, lockedUntil, leverageMultiplier);
emit DepositedAndStaked(msg.sender, usdcAmount, tokenId, fiduAmount, lockedUntil, leverageMultiplier);
}
function lockupPeriodToDuration(LockupPeriod lockupPeriod) internal pure returns (uint256 lockDuration) {
if (lockupPeriod == LockupPeriod.SixMonths) {
return 365 days / 2;
} else if (lockupPeriod == LockupPeriod.TwelveMonths) {
return 365 days;
} else if (lockupPeriod == LockupPeriod.TwentyFourMonths) {
return 365 days * 2;
} else {
revert("unsupported LockupPeriod");
}
}
/// @notice Get the leverage multiplier used to boost rewards for a given lockup period.
/// See `stakeWithLockup`. The leverage multiplier is denominated in `MULTIPLIER_DECIMALS`.
function getLeverageMultiplier(LockupPeriod lockupPeriod) public view returns (uint256) {
uint256 leverageMultiplier = leverageMultipliers[lockupPeriod];
require(leverageMultiplier > 0, "unsupported LockupPeriod");
return leverageMultiplier;
}
/// @notice Identical to `depositAndStakeWithLockup`, except it allows for a signature to be passed that permits
/// this contract to move funds on behalf of the user.
/// @param usdcAmount The amount of USDC to deposit
/// @param lockupPeriod The period over which to lock staked tokens
/// @param v secp256k1 signature component
/// @param r secp256k1 signature component
/// @param s secp256k1 signature component
function depositWithPermitAndStakeWithLockup(
uint256 usdcAmount,
LockupPeriod lockupPeriod,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), usdcAmount, deadline, v, r, s);
depositAndStakeWithLockup(usdcAmount, lockupPeriod);
}
function _stakeWithLockup(
address staker,
address nftRecipient,
uint256 amount,
uint256 lockedUntil,
uint256 leverageMultiplier
) internal returns (uint256 tokenId) {
require(amount > 0, "Cannot stake 0");
_tokenIdTracker.increment();
tokenId = _tokenIdTracker.current();
// Ensure we snapshot accumulatedRewardsPerToken for tokenId after it is available
// We do this before setting the position, because we don't want `earned` to (incorrectly) account for
// position.amount yet. This is equivalent to using the updateReward(msg.sender) modifier in the original
// synthetix contract, where the modifier is called before any staking balance for that address is recorded
_updateReward(tokenId);
positions[tokenId] = StakedPosition({
amount: amount,
rewards: StakingRewardsVesting.Rewards({
totalUnvested: 0,
totalVested: 0,
totalPreviouslyVested: 0,
totalClaimed: 0,
startTime: block.timestamp,
endTime: block.timestamp.add(vestingLength)
}),
leverageMultiplier: leverageMultiplier,
lockedUntil: lockedUntil
});
_mint(nftRecipient, tokenId);
uint256 leveredAmount = positionToLeveredAmount(positions[tokenId]);
totalLeveragedStakedSupply = totalLeveragedStakedSupply.add(leveredAmount);
totalStakedSupply = totalStakedSupply.add(amount);
// Staker is address(this) when using depositAndStake or other convenience functions
if (staker != address(this)) {
stakingToken().safeTransferFrom(staker, address(this), amount);
}
emit Staked(nftRecipient, tokenId, amount, lockedUntil, leverageMultiplier);
return tokenId;
}
/// @notice Unstake an amount of `stakingToken()` associated with a given position and transfer to msg.sender.
/// Unvested rewards will be forfeited, but remaining staked amount will continue to accrue rewards.
/// Positions that are still locked cannot be unstaked until the position's lockedUntil time has passed.
/// @dev This function checkpoints rewards
/// @param tokenId A staking position token ID
/// @param amount Amount of `stakingToken()` to be unstaked from the position
function unstake(uint256 tokenId, uint256 amount) public nonReentrant whenNotPaused updateReward(tokenId) {
_unstake(tokenId, amount);
stakingToken().safeTransfer(msg.sender, amount);
}
function unstakeAndWithdraw(uint256 tokenId, uint256 usdcAmount) public nonReentrant whenNotPaused {
(uint256 usdcReceivedAmount, uint256 fiduAmount) = _unstakeAndWithdraw(tokenId, usdcAmount);
emit UnstakedAndWithdrew(msg.sender, usdcReceivedAmount, tokenId, fiduAmount);
}
function _unstakeAndWithdraw(uint256 tokenId, uint256 usdcAmount)
internal
updateReward(tokenId)
returns (uint256 usdcAmountReceived, uint256 fiduUsed)
{
require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed");
ISeniorPool seniorPool = config.getSeniorPool();
IFidu fidu = config.getFidu();
uint256 fiduBalanceBefore = fidu.balanceOf(address(this));
usdcAmountReceived = seniorPool.withdraw(usdcAmount);
fiduUsed = fiduBalanceBefore.sub(fidu.balanceOf(address(this)));
_unstake(tokenId, fiduUsed);
config.getUSDC().safeTransfer(msg.sender, usdcAmountReceived);
return (usdcAmountReceived, fiduUsed);
}
function unstakeAndWithdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata usdcAmounts)
public
nonReentrant
whenNotPaused
{
require(tokenIds.length == usdcAmounts.length, "tokenIds and usdcAmounts must be the same length");
uint256 usdcReceivedAmountTotal = 0;
uint256[] memory fiduAmounts = new uint256[](usdcAmounts.length);
for (uint256 i = 0; i < usdcAmounts.length; i++) {
(uint256 usdcReceivedAmount, uint256 fiduAmount) = _unstakeAndWithdraw(tokenIds[i], usdcAmounts[i]);
usdcReceivedAmountTotal = usdcReceivedAmountTotal.add(usdcReceivedAmount);
fiduAmounts[i] = fiduAmount;
}
emit UnstakedAndWithdrewMultiple(msg.sender, usdcReceivedAmountTotal, tokenIds, fiduAmounts);
}
function unstakeAndWithdrawInFidu(uint256 tokenId, uint256 fiduAmount) public nonReentrant whenNotPaused {
uint256 usdcReceivedAmount = _unstakeAndWithdrawInFidu(tokenId, fiduAmount);
emit UnstakedAndWithdrew(msg.sender, usdcReceivedAmount, tokenId, fiduAmount);
}
function _unstakeAndWithdrawInFidu(uint256 tokenId, uint256 fiduAmount)
internal
updateReward(tokenId)
returns (uint256 usdcReceivedAmount)
{
usdcReceivedAmount = config.getSeniorPool().withdrawInFidu(fiduAmount);
_unstake(tokenId, fiduAmount);
config.getUSDC().safeTransfer(msg.sender, usdcReceivedAmount);
return usdcReceivedAmount;
}
function unstakeAndWithdrawMultipleInFidu(uint256[] calldata tokenIds, uint256[] calldata fiduAmounts)
public
nonReentrant
whenNotPaused
{
require(tokenIds.length == fiduAmounts.length, "tokenIds and usdcAmounts must be the same length");
uint256 usdcReceivedAmountTotal = 0;
for (uint256 i = 0; i < fiduAmounts.length; i++) {
uint256 usdcReceivedAmount = _unstakeAndWithdrawInFidu(tokenIds[i], fiduAmounts[i]);
usdcReceivedAmountTotal = usdcReceivedAmountTotal.add(usdcReceivedAmount);
}
emit UnstakedAndWithdrewMultiple(msg.sender, usdcReceivedAmountTotal, tokenIds, fiduAmounts);
}
function _unstake(uint256 tokenId, uint256 amount) internal {
require(ownerOf(tokenId) == msg.sender, "access denied");
require(amount > 0, "Cannot unstake 0");
StakedPosition storage position = positions[tokenId];
uint256 prevAmount = position.amount;
require(amount <= prevAmount, "cannot unstake more than staked balance");
require(block.timestamp >= position.lockedUntil, "staked funds are locked");
// By this point, leverageMultiplier should always be 1x due to the reset logic in updateReward.
// But we subtract leveredAmount from totalLeveragedStakedSupply anyway, since that is technically correct.
uint256 leveredAmount = toLeveredAmount(amount, position.leverageMultiplier);
totalLeveragedStakedSupply = totalLeveragedStakedSupply.sub(leveredAmount);
totalStakedSupply = totalStakedSupply.sub(amount);
position.amount = prevAmount.sub(amount);
// Slash unvested rewards
uint256 slashingPercentage = amount.mul(StakingRewardsVesting.PERCENTAGE_DECIMALS).div(prevAmount);
position.rewards.slash(slashingPercentage);
emit Unstaked(msg.sender, tokenId, amount);
}
/// @notice "Kick" a user's reward multiplier. If they are past their lock-up period, their reward
/// multipler will be reset to 1x.
/// @dev This will also checkpoint their rewards up to the current time.
// solhint-disable-next-line no-empty-blocks
function kick(uint256 tokenId) public nonReentrant whenNotPaused updateReward(tokenId) {}
/// @notice Claim rewards for a given staked position
/// @param tokenId A staking position token ID
function getReward(uint256 tokenId) public nonReentrant whenNotPaused updateReward(tokenId) {
require(ownerOf(tokenId) == msg.sender, "access denied");
uint256 reward = claimableRewards(tokenId);
if (reward > 0) {
positions[tokenId].rewards.claim(reward);
rewardsToken().safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, tokenId, reward);
}
}
/// @notice Unstake the position's full amount and claim all rewards
/// @param tokenId A staking position token ID
function exit(uint256 tokenId) external {
unstake(tokenId, positions[tokenId].amount);
getReward(tokenId);
}
function exitAndWithdraw(uint256 tokenId) external {
unstakeAndWithdrawInFidu(tokenId, positions[tokenId].amount);
getReward(tokenId);
}
/* ========== RESTRICTED FUNCTIONS ========== */
/// @notice Transfer rewards from msg.sender, to be used for reward distribution
function loadRewards(uint256 rewards) public onlyAdmin updateReward(0) {
rewardsToken().safeTransferFrom(msg.sender, address(this), rewards);
rewardsAvailable = rewardsAvailable.add(rewards);
emit RewardAdded(rewards);
}
function setRewardsParameters(
uint256 _targetCapacity,
uint256 _minRate,
uint256 _maxRate,
uint256 _minRateAtPercent,
uint256 _maxRateAtPercent
) public onlyAdmin updateReward(0) {
require(_maxRate >= _minRate, "maxRate must be >= then minRate");
require(_maxRateAtPercent <= _minRateAtPercent, "maxRateAtPercent must be <= minRateAtPercent");
targetCapacity = _targetCapacity;
minRate = _minRate;
maxRate = _maxRate;
minRateAtPercent = _minRateAtPercent;
maxRateAtPercent = _maxRateAtPercent;
emit RewardsParametersUpdated(msg.sender, targetCapacity, minRate, maxRate, minRateAtPercent, maxRateAtPercent);
}
function setLeverageMultiplier(LockupPeriod lockupPeriod, uint256 leverageMultiplier)
public
onlyAdmin
updateReward(0)
{
leverageMultipliers[lockupPeriod] = leverageMultiplier;
emit LeverageMultiplierUpdated(msg.sender, lockupPeriod, leverageMultiplier);
}
function setVestingSchedule(uint256 _vestingLength) public onlyAdmin updateReward(0) {
vestingLength = _vestingLength;
emit VestingScheduleUpdated(msg.sender, vestingLength);
}
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(_msgSender(), address(config));
}
/* ========== MODIFIERS ========== */
modifier updateReward(uint256 tokenId) {
_updateReward(tokenId);
_;
}
function _updateReward(uint256 tokenId) internal {
uint256 prevAccumulatedRewardsPerToken = accumulatedRewardsPerToken;
accumulatedRewardsPerToken = rewardPerToken();
uint256 rewardsJustDistributed = totalLeveragedStakedSupply
.mul(accumulatedRewardsPerToken.sub(prevAccumulatedRewardsPerToken))
.div(stakingTokenMantissa());
rewardsAvailable = rewardsAvailable.sub(rewardsJustDistributed);
lastUpdateTime = block.timestamp;
if (tokenId != 0) {
uint256 additionalRewards = earnedSinceLastCheckpoint(tokenId);
StakedPosition storage position = positions[tokenId];
StakingRewardsVesting.Rewards storage rewards = position.rewards;
rewards.totalUnvested = rewards.totalUnvested.add(additionalRewards);
rewards.checkpoint();
positionToAccumulatedRewardsPerToken[tokenId] = accumulatedRewardsPerToken;
// If position is unlocked, reset its leverageMultiplier back to 1x
uint256 lockedUntil = position.lockedUntil;
uint256 leverageMultiplier = position.leverageMultiplier;
uint256 amount = position.amount;
if (lockedUntil > 0 && block.timestamp >= lockedUntil && leverageMultiplier > MULTIPLIER_DECIMALS) {
uint256 prevLeveredAmount = toLeveredAmount(amount, leverageMultiplier);
uint256 newLeveredAmount = toLeveredAmount(amount, MULTIPLIER_DECIMALS);
position.leverageMultiplier = MULTIPLIER_DECIMALS;
totalLeveragedStakedSupply = totalLeveragedStakedSupply.sub(prevLeveredAmount).add(newLeveredAmount);
}
}
}
function isAdmin() public view returns (bool) {
return hasRole(OWNER_ROLE, _msgSender());
}
modifier onlyAdmin() {
require(isAdmin(), "Must have admin role to perform this action");
_;
}
/* ========== EVENTS ========== */
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 indexed tokenId, uint256 amount, uint256 lockedUntil, uint256 multiplier);
event DepositedAndStaked(
address indexed user,
uint256 depositedAmount,
uint256 indexed tokenId,
uint256 amount,
uint256 lockedUntil,
uint256 multiplier
);
event Unstaked(address indexed user, uint256 indexed tokenId, uint256 amount);
event UnstakedAndWithdrew(address indexed user, uint256 usdcReceivedAmount, uint256 indexed tokenId, uint256 amount);
event UnstakedAndWithdrewMultiple(
address indexed user,
uint256 usdcReceivedAmount,
uint256[] tokenIds,
uint256[] amounts
);
event RewardPaid(address indexed user, uint256 indexed tokenId, uint256 reward);
event GoldfinchConfigUpdated(address indexed who, address configAddress);
}
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
pragma solidity ^0.6.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity ^0.6.0;
import "../Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuardUpgradeSafe is Initializable {
bool private _notEntered;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
/*
Only addition is the `decimals` function, which we need, and which both our Fidu and USDC use, along with most ERC20's.
*/
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20withDec is IERC20 {
/**
* @dev Returns the number of decimals used for the token
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./ITranchedPool.sol";
abstract contract ISeniorPool {
uint256 public sharePrice;
uint256 public totalLoansOutstanding;
uint256 public totalWritedowns;
function deposit(uint256 amount) external virtual returns (uint256 depositShares);
function depositWithPermit(
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external virtual returns (uint256 depositShares);
function withdraw(uint256 usdcAmount) external virtual returns (uint256 amount);
function withdrawInFidu(uint256 fiduAmount) external virtual returns (uint256 amount);
function sweepToCompound() public virtual;
function sweepFromCompound() public virtual;
function invest(ITranchedPool pool) public virtual;
function estimateInvestment(ITranchedPool pool) public view virtual returns (uint256);
function redeem(uint256 tokenId) public virtual;
function writedown(uint256 tokenId) public virtual;
function calculateWritedown(uint256 tokenId) public view virtual returns (uint256 writedownAmount);
function assets() public view virtual returns (uint256);
function getNumShares(uint256 amount) public view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "../../interfaces/IGoldfinchConfig.sol";
import "./ConfigOptions.sol";
/**
* @title GoldfinchConfig
* @notice This contract stores mappings of useful "protocol config state", giving a central place
* for all other contracts to access it. For example, the TransactionLimit, or the PoolAddress. These config vars
* are enumerated in the `ConfigOptions` library, and can only be changed by admins of the protocol.
* Note: While this inherits from BaseUpgradeablePausable, it is not deployed as an upgradeable contract (this
* is mostly to save gas costs of having each call go through a proxy)
* @author Goldfinch
*/
contract GoldfinchConfig is BaseUpgradeablePausable {
bytes32 public constant GO_LISTER_ROLE = keccak256("GO_LISTER_ROLE");
mapping(uint256 => address) public addresses;
mapping(uint256 => uint256) public numbers;
mapping(address => bool) public goList;
event AddressUpdated(address owner, uint256 index, address oldValue, address newValue);
event NumberUpdated(address owner, uint256 index, uint256 oldValue, uint256 newValue);
event GoListed(address indexed member);
event NoListed(address indexed member);
bool public valuesInitialized;
function initialize(address owner) public initializer {
require(owner != address(0), "Owner address cannot be empty");
__BaseUpgradeablePausable__init(owner);
_setupRole(GO_LISTER_ROLE, owner);
_setRoleAdmin(GO_LISTER_ROLE, OWNER_ROLE);
}
function setAddress(uint256 addressIndex, address newAddress) public onlyAdmin {
require(addresses[addressIndex] == address(0), "Address has already been initialized");
emit AddressUpdated(msg.sender, addressIndex, addresses[addressIndex], newAddress);
addresses[addressIndex] = newAddress;
}
function setNumber(uint256 index, uint256 newNumber) public onlyAdmin {
emit NumberUpdated(msg.sender, index, numbers[index], newNumber);
numbers[index] = newNumber;
}
function setTreasuryReserve(address newTreasuryReserve) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.TreasuryReserve);
emit AddressUpdated(msg.sender, key, addresses[key], newTreasuryReserve);
addresses[key] = newTreasuryReserve;
}
function setSeniorPoolStrategy(address newStrategy) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.SeniorPoolStrategy);
emit AddressUpdated(msg.sender, key, addresses[key], newStrategy);
addresses[key] = newStrategy;
}
function setCreditLineImplementation(address newAddress) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.CreditLineImplementation);
emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
addresses[key] = newAddress;
}
function setTranchedPoolImplementation(address newAddress) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.TranchedPoolImplementation);
emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
addresses[key] = newAddress;
}
function setBorrowerImplementation(address newAddress) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.BorrowerImplementation);
emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
addresses[key] = newAddress;
}
function setGoldfinchConfig(address newAddress) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.GoldfinchConfig);
emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
addresses[key] = newAddress;
}
function initializeFromOtherConfig(
address _initialConfig,
uint256 numbersLength,
uint256 addressesLength
) public onlyAdmin {
require(!valuesInitialized, "Already initialized values");
IGoldfinchConfig initialConfig = IGoldfinchConfig(_initialConfig);
for (uint256 i = 0; i < numbersLength; i++) {
setNumber(i, initialConfig.getNumber(i));
}
for (uint256 i = 0; i < addressesLength; i++) {
if (getAddress(i) == address(0)) {
setAddress(i, initialConfig.getAddress(i));
}
}
valuesInitialized = true;
}
/**
* @dev Adds a user to go-list
* @param _member address to add to go-list
*/
function addToGoList(address _member) public onlyGoListerRole {
goList[_member] = true;
emit GoListed(_member);
}
/**
* @dev removes a user from go-list
* @param _member address to remove from go-list
*/
function removeFromGoList(address _member) public onlyGoListerRole {
goList[_member] = false;
emit NoListed(_member);
}
/**
* @dev adds many users to go-list at once
* @param _members addresses to ad to go-list
*/
function bulkAddToGoList(address[] calldata _members) external onlyGoListerRole {
for (uint256 i = 0; i < _members.length; i++) {
addToGoList(_members[i]);
}
}
/**
* @dev removes many users from go-list at once
* @param _members addresses to remove from go-list
*/
function bulkRemoveFromGoList(address[] calldata _members) external onlyGoListerRole {
for (uint256 i = 0; i < _members.length; i++) {
removeFromGoList(_members[i]);
}
}
/*
Using custom getters in case we want to change underlying implementation later,
or add checks or validations later on.
*/
function getAddress(uint256 index) public view returns (address) {
return addresses[index];
}
function getNumber(uint256 index) public view returns (uint256) {
return numbers[index];
}
modifier onlyGoListerRole() {
require(hasRole(GO_LISTER_ROLE, _msgSender()), "Must have go-lister role to perform this action");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./GoldfinchConfig.sol";
import "../../interfaces/IPool.sol";
import "../../interfaces/IFidu.sol";
import "../../interfaces/ISeniorPool.sol";
import "../../interfaces/ISeniorPoolStrategy.sol";
import "../../interfaces/ICreditDesk.sol";
import "../../interfaces/IERC20withDec.sol";
import "../../interfaces/ICUSDCContract.sol";
import "../../interfaces/IPoolTokens.sol";
import "../../interfaces/IBackerRewards.sol";
import "../../interfaces/IGoldfinchFactory.sol";
import "../../interfaces/IGo.sol";
/**
* @title ConfigHelper
* @notice A convenience library for getting easy access to other contracts and constants within the
* protocol, through the use of the GoldfinchConfig contract
* @author Goldfinch
*/
library ConfigHelper {
function getPool(GoldfinchConfig config) internal view returns (IPool) {
return IPool(poolAddress(config));
}
function getSeniorPool(GoldfinchConfig config) internal view returns (ISeniorPool) {
return ISeniorPool(seniorPoolAddress(config));
}
function getSeniorPoolStrategy(GoldfinchConfig config) internal view returns (ISeniorPoolStrategy) {
return ISeniorPoolStrategy(seniorPoolStrategyAddress(config));
}
function getUSDC(GoldfinchConfig config) internal view returns (IERC20withDec) {
return IERC20withDec(usdcAddress(config));
}
function getCreditDesk(GoldfinchConfig config) internal view returns (ICreditDesk) {
return ICreditDesk(creditDeskAddress(config));
}
function getFidu(GoldfinchConfig config) internal view returns (IFidu) {
return IFidu(fiduAddress(config));
}
function getCUSDCContract(GoldfinchConfig config) internal view returns (ICUSDCContract) {
return ICUSDCContract(cusdcContractAddress(config));
}
function getPoolTokens(GoldfinchConfig config) internal view returns (IPoolTokens) {
return IPoolTokens(poolTokensAddress(config));
}
function getBackerRewards(GoldfinchConfig config) internal view returns (IBackerRewards) {
return IBackerRewards(backerRewardsAddress(config));
}
function getGoldfinchFactory(GoldfinchConfig config) internal view returns (IGoldfinchFactory) {
return IGoldfinchFactory(goldfinchFactoryAddress(config));
}
function getGFI(GoldfinchConfig config) internal view returns (IERC20withDec) {
return IERC20withDec(gfiAddress(config));
}
function getGo(GoldfinchConfig config) internal view returns (IGo) {
return IGo(goAddress(config));
}
function oneInchAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.OneInch));
}
function creditLineImplementationAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.CreditLineImplementation));
}
function trustedForwarderAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.TrustedForwarder));
}
function configAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchConfig));
}
function poolAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.Pool));
}
function poolTokensAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.PoolTokens));
}
function backerRewardsAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.BackerRewards));
}
function seniorPoolAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPool));
}
function seniorPoolStrategyAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPoolStrategy));
}
function creditDeskAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.CreditDesk));
}
function goldfinchFactoryAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchFactory));
}
function gfiAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.GFI));
}
function fiduAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.Fidu));
}
function cusdcContractAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.CUSDCContract));
}
function usdcAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.USDC));
}
function tranchedPoolAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.TranchedPoolImplementation));
}
function migratedTranchedPoolAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.MigratedTranchedPoolImplementation));
}
function reserveAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.TreasuryReserve));
}
function protocolAdminAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.ProtocolAdmin));
}
function borrowerImplementationAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.BorrowerImplementation));
}
function goAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.Go));
}
function stakingRewardsAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.StakingRewards));
}
function getReserveDenominator(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.ReserveDenominator));
}
function getWithdrawFeeDenominator(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.WithdrawFeeDenominator));
}
function getLatenessGracePeriodInDays(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.LatenessGracePeriodInDays));
}
function getLatenessMaxDays(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.LatenessMaxDays));
}
function getDrawdownPeriodInSeconds(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds));
}
function getTransferRestrictionPeriodInDays(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays));
}
function getLeverageRatio(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.LeverageRatio));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./PauserPausable.sol";
/**
* @title BaseUpgradeablePausable contract
* @notice This is our Base contract that most other contracts inherit from. It includes many standard
* useful abilities like ugpradeability, pausability, access control, and re-entrancy guards.
* @author Goldfinch
*/
contract BaseUpgradeablePausable is
Initializable,
AccessControlUpgradeSafe,
PauserPausable,
ReentrancyGuardUpgradeSafe
{
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
using SafeMath for uint256;
// Pre-reserving a few slots in the base contract in case we need to add things in the future.
// This does not actually take up gas cost or storage cost, but it does reserve the storage slots.
// See OpenZeppelin's use of this pattern here:
// https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/GSN/Context.sol#L37
uint256[50] private __gap1;
uint256[50] private __gap2;
uint256[50] private __gap3;
uint256[50] private __gap4;
// solhint-disable-next-line func-name-mixedcase
function __BaseUpgradeablePausable__init(address owner) public initializer {
require(owner != address(0), "Owner cannot be the zero address");
__AccessControl_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
_setupRole(OWNER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
function isAdmin() public view returns (bool) {
return hasRole(OWNER_ROLE, _msgSender());
}
modifier onlyAdmin() {
require(isAdmin(), "Must have admin role to perform this action");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
library StakingRewardsVesting {
using SafeMath for uint256;
using StakingRewardsVesting for Rewards;
uint256 internal constant PERCENTAGE_DECIMALS = 1e18;
struct Rewards {
uint256 totalUnvested;
uint256 totalVested;
uint256 totalPreviouslyVested;
uint256 totalClaimed;
uint256 startTime;
uint256 endTime;
}
function claim(Rewards storage rewards, uint256 reward) internal {
rewards.totalClaimed = rewards.totalClaimed.add(reward);
}
function claimable(Rewards storage rewards) internal view returns (uint256) {
return rewards.totalVested.add(rewards.totalPreviouslyVested).sub(rewards.totalClaimed);
}
function currentGrant(Rewards storage rewards) internal view returns (uint256) {
return rewards.totalUnvested.add(rewards.totalVested);
}
/// @notice Slash the vesting rewards by `percentage`. `percentage` of the unvested portion
/// of the grant is forfeited. The remaining unvested portion continues to vest over the rest
/// of the vesting schedule. The already vested portion continues to be claimable.
///
/// A motivating example:
///
/// Let's say we're 50% through vesting, with 100 tokens granted. Thus, 50 tokens are vested and 50 are unvested.
/// Now let's say the grant is slashed by 90% (e.g. for StakingRewards, because the user unstaked 90% of their
/// position). 45 of the unvested tokens will be forfeited. 5 of the unvested tokens and 5 of the vested tokens
/// will be considered as the "new grant", which is 50% through vesting. The remaining 45 vested tokens will be
/// still be claimable at any time.
function slash(Rewards storage rewards, uint256 percentage) internal {
require(percentage <= PERCENTAGE_DECIMALS, "slashing percentage cannot be greater than 100%");
uint256 unvestedToSlash = rewards.totalUnvested.mul(percentage).div(PERCENTAGE_DECIMALS);
uint256 vestedToMove = rewards.totalVested.mul(percentage).div(PERCENTAGE_DECIMALS);
rewards.totalUnvested = rewards.totalUnvested.sub(unvestedToSlash);
rewards.totalVested = rewards.totalVested.sub(vestedToMove);
rewards.totalPreviouslyVested = rewards.totalPreviouslyVested.add(vestedToMove);
}
function checkpoint(Rewards storage rewards) internal {
uint256 newTotalVested = totalVestedAt(rewards.startTime, rewards.endTime, block.timestamp, rewards.currentGrant());
if (newTotalVested > rewards.totalVested) {
uint256 difference = newTotalVested.sub(rewards.totalVested);
rewards.totalUnvested = rewards.totalUnvested.sub(difference);
rewards.totalVested = newTotalVested;
}
}
function totalVestedAt(
uint256 start,
uint256 end,
uint256 time,
uint256 grantedAmount
) internal pure returns (uint256) {
if (end <= start) {
return grantedAmount;
}
return Math.min(grantedAmount.mul(time.sub(start)).div(end.sub(start)), grantedAmount);
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IV2CreditLine.sol";
abstract contract ITranchedPool {
IV2CreditLine public creditLine;
uint256 public createdAt;
enum Tranches {
Reserved,
Senior,
Junior
}
struct TrancheInfo {
uint256 id;
uint256 principalDeposited;
uint256 principalSharePrice;
uint256 interestSharePrice;
uint256 lockedUntil;
}
struct PoolSlice {
TrancheInfo seniorTranche;
TrancheInfo juniorTranche;
uint256 totalInterestAccrued;
uint256 principalDeployed;
}
struct SliceInfo {
uint256 reserveFeePercent;
uint256 interestAccrued;
uint256 principalAccrued;
}
struct ApplyResult {
uint256 interestRemaining;
uint256 principalRemaining;
uint256 reserveDeduction;
uint256 oldInterestSharePrice;
uint256 oldPrincipalSharePrice;
}
function initialize(
address _config,
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays,
uint256 _fundableAt,
uint256[] calldata _allowedUIDTypes
) public virtual;
function getTranche(uint256 tranche) external view virtual returns (TrancheInfo memory);
function pay(uint256 amount) external virtual;
function lockJuniorCapital() external virtual;
function lockPool() external virtual;
function initializeNextSlice(uint256 _fundableAt) external virtual;
function totalJuniorDeposits() external view virtual returns (uint256);
function drawdown(uint256 amount) external virtual;
function setFundableAt(uint256 timestamp) external virtual;
function deposit(uint256 tranche, uint256 amount) external virtual returns (uint256 tokenId);
function assess() external virtual;
function depositWithPermit(
uint256 tranche,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external virtual returns (uint256 tokenId);
function availableToWithdraw(uint256 tokenId)
external
view
virtual
returns (uint256 interestRedeemable, uint256 principalRedeemable);
function withdraw(uint256 tokenId, uint256 amount)
external
virtual
returns (uint256 interestWithdrawn, uint256 principalWithdrawn);
function withdrawMax(uint256 tokenId)
external
virtual
returns (uint256 interestWithdrawn, uint256 principalWithdrawn);
function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./ICreditLine.sol";
abstract contract IV2CreditLine is ICreditLine {
function principal() external view virtual returns (uint256);
function totalInterestAccrued() external view virtual returns (uint256);
function termStartTime() external view virtual returns (uint256);
function setLimit(uint256 newAmount) external virtual;
function setMaxLimit(uint256 newAmount) external virtual;
function setBalance(uint256 newBalance) external virtual;
function setPrincipal(uint256 _principal) external virtual;
function setTotalInterestAccrued(uint256 _interestAccrued) external virtual;
function drawdown(uint256 amount) external virtual;
function assess()
external
virtual
returns (
uint256,
uint256,
uint256
);
function initialize(
address _config,
address owner,
address _borrower,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays
) public virtual;
function setTermEndTime(uint256 newTermEndTime) external virtual;
function setNextDueTime(uint256 newNextDueTime) external virtual;
function setInterestOwed(uint256 newInterestOwed) external virtual;
function setPrincipalOwed(uint256 newPrincipalOwed) external virtual;
function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) external virtual;
function setWritedownAmount(uint256 newWritedownAmount) external virtual;
function setLastFullPaymentTime(uint256 newLastFullPaymentTime) external virtual;
function setLateFeeApr(uint256 newLateFeeApr) external virtual;
function updateGoldfinchConfig() external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface ICreditLine {
function borrower() external view returns (address);
function limit() external view returns (uint256);
function maxLimit() external view returns (uint256);
function interestApr() external view returns (uint256);
function paymentPeriodInDays() external view returns (uint256);
function principalGracePeriodInDays() external view returns (uint256);
function termInDays() external view returns (uint256);
function lateFeeApr() external view returns (uint256);
function isLate() external view returns (bool);
function withinPrincipalGracePeriod() external view returns (bool);
// Accounting variables
function balance() external view returns (uint256);
function interestOwed() external view returns (uint256);
function principalOwed() external view returns (uint256);
function termEndTime() external view returns (uint256);
function nextDueTime() external view returns (uint256);
function interestAccruedAsOf() external view returns (uint256);
function lastFullPaymentTime() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IGoldfinchConfig {
function getNumber(uint256 index) external returns (uint256);
function getAddress(uint256 index) external returns (address);
function setAddress(uint256 index, address newAddress) external returns (address);
function setNumber(uint256 index, uint256 newNumber) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/**
* @title ConfigOptions
* @notice A central place for enumerating the configurable options of our GoldfinchConfig contract
* @author Goldfinch
*/
library ConfigOptions {
// NEVER EVER CHANGE THE ORDER OF THESE!
// You can rename or append. But NEVER change the order.
enum Numbers {
TransactionLimit,
TotalFundsLimit,
MaxUnderwriterLimit,
ReserveDenominator,
WithdrawFeeDenominator,
LatenessGracePeriodInDays,
LatenessMaxDays,
DrawdownPeriodInSeconds,
TransferRestrictionPeriodInDays,
LeverageRatio
}
enum Addresses {
Pool,
CreditLineImplementation,
GoldfinchFactory,
CreditDesk,
Fidu,
USDC,
TreasuryReserve,
ProtocolAdmin,
OneInch,
TrustedForwarder,
CUSDCContract,
GoldfinchConfig,
PoolTokens,
TranchedPoolImplementation,
SeniorPool,
SeniorPoolStrategy,
MigratedTranchedPoolImplementation,
BorrowerImplementation,
GFI,
Go,
BackerRewards,
StakingRewards
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
/**
* @title PauserPausable
* @notice Inheriting from OpenZeppelin's Pausable contract, this does small
* augmentations to make it work with a PAUSER_ROLE, leveraging the AccessControl contract.
* It is meant to be inherited.
* @author Goldfinch
*/
contract PauserPausable is AccessControlUpgradeSafe, PausableUpgradeSafe {
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
// solhint-disable-next-line func-name-mixedcase
function __PauserPausable__init() public initializer {
__Pausable_init_unchained();
}
/**
* @dev Pauses all functions guarded by Pause
*
* See {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the PAUSER_ROLE.
*/
function pause() public onlyPauserRole {
_pause();
}
/**
* @dev Unpauses the contract
*
* See {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the Pauser role
*/
function unpause() public onlyPauserRole {
_unpause();
}
modifier onlyPauserRole() {
require(hasRole(PAUSER_ROLE, _msgSender()), "Must have pauser role to perform this action");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
abstract contract IPool {
uint256 public sharePrice;
function deposit(uint256 amount) external virtual;
function withdraw(uint256 usdcAmount) external virtual;
function withdrawInFidu(uint256 fiduAmount) external virtual;
function collectInterestAndPrincipal(
address from,
uint256 interest,
uint256 principal
) public virtual;
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool);
function drawdown(address to, uint256 amount) public virtual returns (bool);
function sweepToCompound() public virtual;
function sweepFromCompound() public virtual;
function distributeLosses(address creditlineAddress, int256 writedownDelta) external virtual;
function assets() public view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IERC20withDec.sol";
interface IFidu is IERC20withDec {
function mintTo(address to, uint256 amount) external;
function burnFrom(address to, uint256 amount) external;
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./ISeniorPool.sol";
import "./ITranchedPool.sol";
abstract contract ISeniorPoolStrategy {
function getLeverageRatio(ITranchedPool pool) public view virtual returns (uint256);
function invest(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256 amount);
function estimateInvestment(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
abstract contract ICreditDesk {
uint256 public totalWritedowns;
uint256 public totalLoansOutstanding;
function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit) external virtual;
function drawdown(address creditLineAddress, uint256 amount) external virtual;
function pay(address creditLineAddress, uint256 amount) external virtual;
function assessCreditLine(address creditLineAddress) external virtual;
function applyPayment(address creditLineAddress, uint256 amount) external virtual;
function getNextPaymentAmount(address creditLineAddress, uint256 asOfBLock) external view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
// Taken from https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IERC20withDec.sol";
interface ICUSDCContract is IERC20withDec {
/*** User Interface ***/
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);
function liquidateBorrow(
address borrower,
uint256 repayAmount,
address cTokenCollateral
) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function balanceOfUnderlying(address owner) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
/*** Admin Functions ***/
function _addReserves(uint256 addAmount) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol";
interface IPoolTokens is IERC721 {
event TokenMinted(
address indexed owner,
address indexed pool,
uint256 indexed tokenId,
uint256 amount,
uint256 tranche
);
event TokenRedeemed(
address indexed owner,
address indexed pool,
uint256 indexed tokenId,
uint256 principalRedeemed,
uint256 interestRedeemed,
uint256 tranche
);
event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId);
struct TokenInfo {
address pool;
uint256 tranche;
uint256 principalAmount;
uint256 principalRedeemed;
uint256 interestRedeemed;
}
struct MintParams {
uint256 principalAmount;
uint256 tranche;
}
function mint(MintParams calldata params, address to) external returns (uint256);
function redeem(
uint256 tokenId,
uint256 principalRedeemed,
uint256 interestRedeemed
) external;
function burn(uint256 tokenId) external;
function onPoolCreated(address newPool) external;
function getTokenInfo(uint256 tokenId) external view returns (TokenInfo memory);
function validPool(address sender) external view returns (bool);
function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IBackerRewards {
function allocateRewards(uint256 _interestPaymentAmount) external;
function setPoolTokenAccRewardsPerPrincipalDollarAtMint(address poolAddress, uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IGoldfinchFactory {
function createCreditLine() external returns (address);
function createBorrower(address owner) external returns (address);
function createPool(
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256[] calldata _allowedUIDTypes
) external returns (address);
function createMigratedPool(
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256[] calldata _allowedUIDTypes
) external returns (address);
function updateGoldfinchConfig() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
abstract contract IGo {
uint256 public constant ID_TYPE_0 = 0;
uint256 public constant ID_TYPE_1 = 1;
uint256 public constant ID_TYPE_2 = 2;
uint256 public constant ID_TYPE_3 = 3;
uint256 public constant ID_TYPE_4 = 4;
uint256 public constant ID_TYPE_5 = 5;
uint256 public constant ID_TYPE_6 = 6;
uint256 public constant ID_TYPE_7 = 7;
uint256 public constant ID_TYPE_8 = 8;
uint256 public constant ID_TYPE_9 = 9;
uint256 public constant ID_TYPE_10 = 10;
/// @notice Returns the address of the UniqueIdentity contract.
function uniqueIdentity() external virtual returns (address);
function go(address account) public view virtual returns (bool);
function goOnlyIdTypes(address account, uint256[] calldata onlyIdTypes) public view virtual returns (bool);
function goSeniorPool(address account) public view virtual returns (bool);
function updateGoldfinchConfig() external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "../protocol/core/BaseUpgradeablePausable.sol";
import "../protocol/core/Pool.sol";
import "../protocol/core/Accountant.sol";
import "../protocol/core/CreditLine.sol";
import "../protocol/core/GoldfinchConfig.sol";
contract FakeV2CreditDesk is BaseUpgradeablePausable {
uint256 public totalWritedowns;
uint256 public totalLoansOutstanding;
uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;
GoldfinchConfig public config;
struct Underwriter {
uint256 governanceLimit;
address[] creditLines;
}
struct Borrower {
address[] creditLines;
}
event PaymentMade(
address indexed payer,
address indexed creditLine,
uint256 interestAmount,
uint256 principalAmount,
uint256 remainingAmount
);
event PrepaymentMade(address indexed payer, address indexed creditLine, uint256 prepaymentAmount);
event DrawdownMade(address indexed borrower, address indexed creditLine, uint256 drawdownAmount);
event CreditLineCreated(address indexed borrower, address indexed creditLine);
event PoolAddressUpdated(address indexed oldAddress, address indexed newAddress);
event GovernanceUpdatedUnderwriterLimit(address indexed underwriter, uint256 newLimit);
event LimitChanged(address indexed owner, string limitType, uint256 amount);
mapping(address => Underwriter) public underwriters;
mapping(address => Borrower) private borrowers;
function initialize(address owner, GoldfinchConfig _config) public initializer {
owner;
_config;
return;
}
function someBrandNewFunction() public pure returns (uint256) {
return 5;
}
function getUnderwriterCreditLines(address underwriterAddress) public view returns (address[] memory) {
return underwriters[underwriterAddress].creditLines;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
/**
* @title Goldfinch's Pool contract
* @notice Main entry point for LP's (a.k.a. capital providers)
* Handles key logic for depositing and withdrawing funds from the Pool
* @author Goldfinch
*/
contract Pool is BaseUpgradeablePausable, IPool {
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
uint256 public compoundBalance;
event DepositMade(address indexed capitalProvider, uint256 amount, uint256 shares);
event WithdrawalMade(address indexed capitalProvider, uint256 userAmount, uint256 reserveAmount);
event TransferMade(address indexed from, address indexed to, uint256 amount);
event InterestCollected(address indexed payer, uint256 poolAmount, uint256 reserveAmount);
event PrincipalCollected(address indexed payer, uint256 amount);
event ReserveFundsCollected(address indexed user, uint256 amount);
event PrincipalWrittendown(address indexed creditline, int256 amount);
event GoldfinchConfigUpdated(address indexed who, address configAddress);
/**
* @notice Run only once, on initialization
* @param owner The address of who should have the "OWNER_ROLE" of this contract
* @param _config The address of the GoldfinchConfig contract
*/
function initialize(address owner, GoldfinchConfig _config) public initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = _config;
sharePrice = fiduMantissa();
IERC20withDec usdc = config.getUSDC();
// Sanity check the address
usdc.totalSupply();
// Unlock self for infinite amount
bool success = usdc.approve(address(this), uint256(-1));
require(success, "Failed to approve USDC");
}
/**
* @notice Deposits `amount` USDC from msg.sender into the Pool, and returns you the equivalent value of FIDU tokens
* @param amount The amount of USDC to deposit
*/
function deposit(uint256 amount) external override whenNotPaused withinTransactionLimit(amount) nonReentrant {
require(amount > 0, "Must deposit more than zero");
// Check if the amount of new shares to be added is within limits
uint256 depositShares = getNumShares(amount);
uint256 potentialNewTotalShares = totalShares().add(depositShares);
require(poolWithinLimit(potentialNewTotalShares), "Deposit would put the Pool over the total limit.");
emit DepositMade(msg.sender, amount, depositShares);
bool success = doUSDCTransfer(msg.sender, address(this), amount);
require(success, "Failed to transfer for deposit");
config.getFidu().mintTo(msg.sender, depositShares);
}
/**
* @notice Withdraws USDC from the Pool to msg.sender, and burns the equivalent value of FIDU tokens
* @param usdcAmount The amount of USDC to withdraw
*/
function withdraw(uint256 usdcAmount) external override whenNotPaused nonReentrant {
require(usdcAmount > 0, "Must withdraw more than zero");
// This MUST happen before calculating withdrawShares, otherwise the share price
// changes between calculation and burning of Fidu, which creates a asset/liability mismatch
if (compoundBalance > 0) {
_sweepFromCompound();
}
uint256 withdrawShares = getNumShares(usdcAmount);
_withdraw(usdcAmount, withdrawShares);
}
/**
* @notice Withdraws USDC (denominated in FIDU terms) from the Pool to msg.sender
* @param fiduAmount The amount of USDC to withdraw in terms of fidu shares
*/
function withdrawInFidu(uint256 fiduAmount) external override whenNotPaused nonReentrant {
require(fiduAmount > 0, "Must withdraw more than zero");
if (compoundBalance > 0) {
_sweepFromCompound();
}
uint256 usdcAmount = getUSDCAmountFromShares(fiduAmount);
uint256 withdrawShares = fiduAmount;
_withdraw(usdcAmount, withdrawShares);
}
/**
* @notice Collects `interest` USDC in interest and `principal` in principal from `from` and sends it to the Pool.
* This also increases the share price accordingly. A portion is sent to the Goldfinch Reserve address
* @param from The address to take the USDC from. Implicitly, the Pool
* must be authorized to move USDC on behalf of `from`.
* @param interest the interest amount of USDC to move to the Pool
* @param principal the principal amount of USDC to move to the Pool
*
* Requirements:
* - The caller must be the Credit Desk. Not even the owner can call this function.
*/
function collectInterestAndPrincipal(
address from,
uint256 interest,
uint256 principal
) public override onlyCreditDesk whenNotPaused {
_collectInterestAndPrincipal(from, interest, principal);
}
function distributeLosses(address creditlineAddress, int256 writedownDelta)
external
override
onlyCreditDesk
whenNotPaused
{
if (writedownDelta > 0) {
uint256 delta = usdcToSharePrice(uint256(writedownDelta));
sharePrice = sharePrice.add(delta);
} else {
// If delta is negative, convert to positive uint, and sub from sharePrice
uint256 delta = usdcToSharePrice(uint256(writedownDelta * -1));
sharePrice = sharePrice.sub(delta);
}
emit PrincipalWrittendown(creditlineAddress, writedownDelta);
}
/**
* @notice Moves `amount` USDC from `from`, to `to`.
* @param from The address to take the USDC from. Implicitly, the Pool
* must be authorized to move USDC on behalf of `from`.
* @param to The address that the USDC should be moved to
* @param amount the amount of USDC to move to the Pool
*
* Requirements:
* - The caller must be the Credit Desk. Not even the owner can call this function.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public override onlyCreditDesk whenNotPaused returns (bool) {
bool result = doUSDCTransfer(from, to, amount);
require(result, "USDC Transfer failed");
emit TransferMade(from, to, amount);
return result;
}
/**
* @notice Moves `amount` USDC from the pool, to `to`. This is similar to transferFrom except we sweep any
* balance we have from compound first and recognize interest. Meant to be called only by the credit desk on drawdown
* @param to The address that the USDC should be moved to
* @param amount the amount of USDC to move to the Pool
*
* Requirements:
* - The caller must be the Credit Desk. Not even the owner can call this function.
*/
function drawdown(address to, uint256 amount) public override onlyCreditDesk whenNotPaused returns (bool) {
if (compoundBalance > 0) {
_sweepFromCompound();
}
return transferFrom(address(this), to, amount);
}
function assets() public view override returns (uint256) {
ICreditDesk creditDesk = config.getCreditDesk();
return
compoundBalance.add(config.getUSDC().balanceOf(address(this))).add(creditDesk.totalLoansOutstanding()).sub(
creditDesk.totalWritedowns()
);
}
function migrateToSeniorPool() external onlyAdmin {
// Bring back all USDC
if (compoundBalance > 0) {
sweepFromCompound();
}
// Pause deposits/withdrawals
if (!paused()) {
pause();
}
// Remove special priveldges from Fidu
bytes32 minterRole = keccak256("MINTER_ROLE");
bytes32 pauserRole = keccak256("PAUSER_ROLE");
config.getFidu().renounceRole(minterRole, address(this));
config.getFidu().renounceRole(pauserRole, address(this));
// Move all USDC to the SeniorPool
address seniorPoolAddress = config.seniorPoolAddress();
uint256 balance = config.getUSDC().balanceOf(address(this));
bool success = doUSDCTransfer(address(this), seniorPoolAddress, balance);
require(success, "Failed to transfer USDC balance to the senior pool");
// Claim our COMP!
address compoundController = address(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
bytes memory data = abi.encodeWithSignature("claimComp(address)", address(this));
bytes memory _res;
// solhint-disable-next-line avoid-low-level-calls
(success, _res) = compoundController.call(data);
require(success, "Failed to claim COMP");
// Send our balance of COMP!
address compToken = address(0xc00e94Cb662C3520282E6f5717214004A7f26888);
data = abi.encodeWithSignature("balanceOf(address)", address(this));
// solhint-disable-next-line avoid-low-level-calls
(success, _res) = compToken.call(data);
uint256 compBalance = toUint256(_res);
data = abi.encodeWithSignature("transfer(address,uint256)", seniorPoolAddress, compBalance);
// solhint-disable-next-line avoid-low-level-calls
(success, _res) = compToken.call(data);
require(success, "Failed to transfer COMP");
}
function toUint256(bytes memory _bytes) internal pure returns (uint256 value) {
assembly {
value := mload(add(_bytes, 0x20))
}
}
/**
* @notice Moves any USDC still in the Pool to Compound, and tracks the amount internally.
* This is done to earn interest on latent funds until we have other borrowers who can use it.
*
* Requirements:
* - The caller must be an admin.
*/
function sweepToCompound() public override onlyAdmin whenNotPaused {
IERC20 usdc = config.getUSDC();
uint256 usdcBalance = usdc.balanceOf(address(this));
ICUSDCContract cUSDC = config.getCUSDCContract();
// Approve compound to the exact amount
bool success = usdc.approve(address(cUSDC), usdcBalance);
require(success, "Failed to approve USDC for compound");
sweepToCompound(cUSDC, usdcBalance);
// Remove compound approval to be extra safe
success = config.getUSDC().approve(address(cUSDC), 0);
require(success, "Failed to approve USDC for compound");
}
/**
* @notice Moves any USDC from Compound back to the Pool, and recognizes interest earned.
* This is done automatically on drawdown or withdraw, but can be called manually if necessary.
*
* Requirements:
* - The caller must be an admin.
*/
function sweepFromCompound() public override onlyAdmin whenNotPaused {
_sweepFromCompound();
}
/* Internal Functions */
function _withdraw(uint256 usdcAmount, uint256 withdrawShares) internal withinTransactionLimit(usdcAmount) {
IFidu fidu = config.getFidu();
// Determine current shares the address has and the shares requested to withdraw
uint256 currentShares = fidu.balanceOf(msg.sender);
// Ensure the address has enough value in the pool
require(withdrawShares <= currentShares, "Amount requested is greater than what this address owns");
uint256 reserveAmount = usdcAmount.div(config.getWithdrawFeeDenominator());
uint256 userAmount = usdcAmount.sub(reserveAmount);
emit WithdrawalMade(msg.sender, userAmount, reserveAmount);
// Send the amounts
bool success = doUSDCTransfer(address(this), msg.sender, userAmount);
require(success, "Failed to transfer for withdraw");
sendToReserve(address(this), reserveAmount, msg.sender);
// Burn the shares
fidu.burnFrom(msg.sender, withdrawShares);
}
function sweepToCompound(ICUSDCContract cUSDC, uint256 usdcAmount) internal {
// Our current design requires we re-normalize by withdrawing everything and recognizing interest gains
// before we can add additional capital to Compound
require(compoundBalance == 0, "Cannot sweep when we already have a compound balance");
require(usdcAmount != 0, "Amount to sweep cannot be zero");
uint256 error = cUSDC.mint(usdcAmount);
require(error == 0, "Sweep to compound failed");
compoundBalance = usdcAmount;
}
function sweepFromCompound(ICUSDCContract cUSDC, uint256 cUSDCAmount) internal {
uint256 cBalance = compoundBalance;
require(cBalance != 0, "No funds on compound");
require(cUSDCAmount != 0, "Amount to sweep cannot be zero");
IERC20 usdc = config.getUSDC();
uint256 preRedeemUSDCBalance = usdc.balanceOf(address(this));
uint256 cUSDCExchangeRate = cUSDC.exchangeRateCurrent();
uint256 redeemedUSDC = cUSDCToUSDC(cUSDCExchangeRate, cUSDCAmount);
uint256 error = cUSDC.redeem(cUSDCAmount);
uint256 postRedeemUSDCBalance = usdc.balanceOf(address(this));
require(error == 0, "Sweep from compound failed");
require(postRedeemUSDCBalance.sub(preRedeemUSDCBalance) == redeemedUSDC, "Unexpected redeem amount");
uint256 interestAccrued = redeemedUSDC.sub(cBalance);
_collectInterestAndPrincipal(address(this), interestAccrued, 0);
compoundBalance = 0;
}
function _collectInterestAndPrincipal(
address from,
uint256 interest,
uint256 principal
) internal {
uint256 reserveAmount = interest.div(config.getReserveDenominator());
uint256 poolAmount = interest.sub(reserveAmount);
uint256 increment = usdcToSharePrice(poolAmount);
sharePrice = sharePrice.add(increment);
if (poolAmount > 0) {
emit InterestCollected(from, poolAmount, reserveAmount);
}
if (principal > 0) {
emit PrincipalCollected(from, principal);
}
if (reserveAmount > 0) {
sendToReserve(from, reserveAmount, from);
}
// Gas savings: No need to transfer to yourself, which happens in sweepFromCompound
if (from != address(this)) {
bool success = doUSDCTransfer(from, address(this), principal.add(poolAmount));
require(success, "Failed to collect principal repayment");
}
}
function _sweepFromCompound() internal {
ICUSDCContract cUSDC = config.getCUSDCContract();
sweepFromCompound(cUSDC, cUSDC.balanceOf(address(this)));
}
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
function fiduMantissa() internal pure returns (uint256) {
return uint256(10)**uint256(18);
}
function usdcMantissa() internal pure returns (uint256) {
return uint256(10)**uint256(6);
}
function usdcToFidu(uint256 amount) internal pure returns (uint256) {
return amount.mul(fiduMantissa()).div(usdcMantissa());
}
function cUSDCToUSDC(uint256 exchangeRate, uint256 amount) internal pure returns (uint256) {
// See https://compound.finance/docs#protocol-math
// But note, the docs and reality do not agree. Docs imply that that exchange rate is
// scaled by 1e18, but tests and mainnet forking make it appear to be scaled by 1e16
// 1e16 is also what Sheraz at Certik said.
uint256 usdcDecimals = 6;
uint256 cUSDCDecimals = 8;
// We multiply in the following order, for the following reasons...
// Amount in cToken (1e8)
// Amount in USDC (but scaled by 1e16, cause that's what exchange rate decimals are)
// Downscale to cToken decimals (1e8)
// Downscale from cToken to USDC decimals (8 to 6)
return amount.mul(exchangeRate).div(10**(18 + usdcDecimals - cUSDCDecimals)).div(10**2);
}
function totalShares() internal view returns (uint256) {
return config.getFidu().totalSupply();
}
function usdcToSharePrice(uint256 usdcAmount) internal view returns (uint256) {
return usdcToFidu(usdcAmount).mul(fiduMantissa()).div(totalShares());
}
function poolWithinLimit(uint256 _totalShares) internal view returns (bool) {
return
_totalShares.mul(sharePrice).div(fiduMantissa()) <=
usdcToFidu(config.getNumber(uint256(ConfigOptions.Numbers.TotalFundsLimit)));
}
function transactionWithinLimit(uint256 amount) internal view returns (bool) {
return amount <= config.getNumber(uint256(ConfigOptions.Numbers.TransactionLimit));
}
function getNumShares(uint256 amount) internal view returns (uint256) {
return usdcToFidu(amount).mul(fiduMantissa()).div(sharePrice);
}
function getUSDCAmountFromShares(uint256 fiduAmount) internal view returns (uint256) {
return fiduToUSDC(fiduAmount.mul(sharePrice).div(fiduMantissa()));
}
function fiduToUSDC(uint256 amount) internal pure returns (uint256) {
return amount.div(fiduMantissa().div(usdcMantissa()));
}
function sendToReserve(
address from,
uint256 amount,
address userForEvent
) internal {
emit ReserveFundsCollected(userForEvent, amount);
bool success = doUSDCTransfer(from, config.reserveAddress(), amount);
require(success, "Reserve transfer was not successful");
}
function doUSDCTransfer(
address from,
address to,
uint256 amount
) internal returns (bool) {
require(to != address(0), "Can't send to zero address");
IERC20withDec usdc = config.getUSDC();
return usdc.transferFrom(from, to, amount);
}
modifier withinTransactionLimit(uint256 amount) {
require(transactionWithinLimit(amount), "Amount is over the per-transaction limit");
_;
}
modifier onlyCreditDesk() {
require(msg.sender == config.creditDeskAddress(), "Only the credit desk is allowed to call this function");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./CreditLine.sol";
import "../../interfaces/ICreditLine.sol";
import "../../external/FixedPoint.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/**
* @title The Accountant
* @notice Library for handling key financial calculations, such as interest and principal accrual.
* @author Goldfinch
*/
library Accountant {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Signed;
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for int256;
using FixedPoint for uint256;
// Scaling factor used by FixedPoint.sol. We need this to convert the fixed point raw values back to unscaled
uint256 public constant FP_SCALING_FACTOR = 10**18;
uint256 public constant INTEREST_DECIMALS = 1e18;
uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;
uint256 public constant SECONDS_PER_YEAR = (SECONDS_PER_DAY * 365);
struct PaymentAllocation {
uint256 interestPayment;
uint256 principalPayment;
uint256 additionalBalancePayment;
}
function calculateInterestAndPrincipalAccrued(
CreditLine cl,
uint256 timestamp,
uint256 lateFeeGracePeriod
) public view returns (uint256, uint256) {
uint256 balance = cl.balance(); // gas optimization
uint256 interestAccrued = calculateInterestAccrued(cl, balance, timestamp, lateFeeGracePeriod);
uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, timestamp);
return (interestAccrued, principalAccrued);
}
function calculateInterestAndPrincipalAccruedOverPeriod(
CreditLine cl,
uint256 balance,
uint256 startTime,
uint256 endTime,
uint256 lateFeeGracePeriod
) public view returns (uint256, uint256) {
uint256 interestAccrued = calculateInterestAccruedOverPeriod(cl, balance, startTime, endTime, lateFeeGracePeriod);
uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, endTime);
return (interestAccrued, principalAccrued);
}
function calculatePrincipalAccrued(
ICreditLine cl,
uint256 balance,
uint256 timestamp
) public view returns (uint256) {
// If we've already accrued principal as of the term end time, then don't accrue more principal
uint256 termEndTime = cl.termEndTime();
if (cl.interestAccruedAsOf() >= termEndTime) {
return 0;
}
if (timestamp >= termEndTime) {
return balance;
} else {
return 0;
}
}
function calculateWritedownFor(
ICreditLine cl,
uint256 timestamp,
uint256 gracePeriodInDays,
uint256 maxDaysLate
) public view returns (uint256, uint256) {
return calculateWritedownForPrincipal(cl, cl.balance(), timestamp, gracePeriodInDays, maxDaysLate);
}
function calculateWritedownForPrincipal(
ICreditLine cl,
uint256 principal,
uint256 timestamp,
uint256 gracePeriodInDays,
uint256 maxDaysLate
) public view returns (uint256, uint256) {
FixedPoint.Unsigned memory amountOwedPerDay = calculateAmountOwedForOneDay(cl);
if (amountOwedPerDay.isEqual(0)) {
return (0, 0);
}
FixedPoint.Unsigned memory fpGracePeriod = FixedPoint.fromUnscaledUint(gracePeriodInDays);
FixedPoint.Unsigned memory daysLate;
// Excel math: =min(1,max(0,periods_late_in_days-graceperiod_in_days)/MAX_ALLOWED_DAYS_LATE) grace_period = 30,
// Before the term end date, we use the interestOwed to calculate the periods late. However, after the loan term
// has ended, since the interest is a much smaller fraction of the principal, we cannot reliably use interest to
// calculate the periods later.
uint256 totalOwed = cl.interestOwed().add(cl.principalOwed());
daysLate = FixedPoint.fromUnscaledUint(totalOwed).div(amountOwedPerDay);
if (timestamp > cl.termEndTime()) {
uint256 secondsLate = timestamp.sub(cl.termEndTime());
daysLate = daysLate.add(FixedPoint.fromUnscaledUint(secondsLate).div(SECONDS_PER_DAY));
}
FixedPoint.Unsigned memory maxLate = FixedPoint.fromUnscaledUint(maxDaysLate);
FixedPoint.Unsigned memory writedownPercent;
if (daysLate.isLessThanOrEqual(fpGracePeriod)) {
// Within the grace period, we don't have to write down, so assume 0%
writedownPercent = FixedPoint.fromUnscaledUint(0);
} else {
writedownPercent = FixedPoint.min(FixedPoint.fromUnscaledUint(1), (daysLate.sub(fpGracePeriod)).div(maxLate));
}
FixedPoint.Unsigned memory writedownAmount = writedownPercent.mul(principal).div(FP_SCALING_FACTOR);
// This will return a number between 0-100 representing the write down percent with no decimals
uint256 unscaledWritedownPercent = writedownPercent.mul(100).div(FP_SCALING_FACTOR).rawValue;
return (unscaledWritedownPercent, writedownAmount.rawValue);
}
function calculateAmountOwedForOneDay(ICreditLine cl) public view returns (FixedPoint.Unsigned memory interestOwed) {
// Determine theoretical interestOwed for one full day
uint256 totalInterestPerYear = cl.balance().mul(cl.interestApr()).div(INTEREST_DECIMALS);
interestOwed = FixedPoint.fromUnscaledUint(totalInterestPerYear).div(365);
return interestOwed;
}
function calculateInterestAccrued(
CreditLine cl,
uint256 balance,
uint256 timestamp,
uint256 lateFeeGracePeriodInDays
) public view returns (uint256) {
// We use Math.min here to prevent integer overflow (ie. go negative) when calculating
// numSecondsElapsed. Typically this shouldn't be possible, because
// the interestAccruedAsOf couldn't be *after* the current timestamp. However, when assessing
// we allow this function to be called with a past timestamp, which raises the possibility
// of overflow.
// This use of min should not generate incorrect interest calculations, since
// this function's purpose is just to normalize balances, and handing in a past timestamp
// will necessarily return zero interest accrued (because zero elapsed time), which is correct.
uint256 startTime = Math.min(timestamp, cl.interestAccruedAsOf());
return calculateInterestAccruedOverPeriod(cl, balance, startTime, timestamp, lateFeeGracePeriodInDays);
}
function calculateInterestAccruedOverPeriod(
CreditLine cl,
uint256 balance,
uint256 startTime,
uint256 endTime,
uint256 lateFeeGracePeriodInDays
) public view returns (uint256 interestOwed) {
uint256 secondsElapsed = endTime.sub(startTime);
uint256 totalInterestPerYear = balance.mul(cl.interestApr()).div(INTEREST_DECIMALS);
interestOwed = totalInterestPerYear.mul(secondsElapsed).div(SECONDS_PER_YEAR);
if (lateFeeApplicable(cl, endTime, lateFeeGracePeriodInDays)) {
uint256 lateFeeInterestPerYear = balance.mul(cl.lateFeeApr()).div(INTEREST_DECIMALS);
uint256 additionalLateFeeInterest = lateFeeInterestPerYear.mul(secondsElapsed).div(SECONDS_PER_YEAR);
interestOwed = interestOwed.add(additionalLateFeeInterest);
}
return interestOwed;
}
function lateFeeApplicable(
CreditLine cl,
uint256 timestamp,
uint256 gracePeriodInDays
) public view returns (bool) {
uint256 secondsLate = timestamp.sub(cl.lastFullPaymentTime());
return cl.lateFeeApr() > 0 && secondsLate > gracePeriodInDays.mul(SECONDS_PER_DAY);
}
function allocatePayment(
uint256 paymentAmount,
uint256 balance,
uint256 interestOwed,
uint256 principalOwed
) public pure returns (PaymentAllocation memory) {
uint256 paymentRemaining = paymentAmount;
uint256 interestPayment = Math.min(interestOwed, paymentRemaining);
paymentRemaining = paymentRemaining.sub(interestPayment);
uint256 principalPayment = Math.min(principalOwed, paymentRemaining);
paymentRemaining = paymentRemaining.sub(principalPayment);
uint256 balanceRemaining = balance.sub(principalPayment);
uint256 additionalBalancePayment = Math.min(paymentRemaining, balanceRemaining);
return
PaymentAllocation({
interestPayment: interestPayment,
principalPayment: principalPayment,
additionalBalancePayment: additionalBalancePayment
});
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./GoldfinchConfig.sol";
import "./ConfigHelper.sol";
import "./BaseUpgradeablePausable.sol";
import "./Accountant.sol";
import "../../interfaces/IERC20withDec.sol";
import "../../interfaces/ICreditLine.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
/**
* @title CreditLine
* @notice A contract that represents the agreement between Backers and
* a Borrower. Includes the terms of the loan, as well as the current accounting state, such as interest owed.
* A CreditLine belongs to a TranchedPool, and is fully controlled by that TranchedPool. It does not
* operate in any standalone capacity. It should generally be considered internal to the TranchedPool.
* @author Goldfinch
*/
// solhint-disable-next-line max-states-count
contract CreditLine is BaseUpgradeablePausable, ICreditLine {
uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;
event GoldfinchConfigUpdated(address indexed who, address configAddress);
// Credit line terms
address public override borrower;
uint256 public currentLimit;
uint256 public override maxLimit;
uint256 public override interestApr;
uint256 public override paymentPeriodInDays;
uint256 public override termInDays;
uint256 public override principalGracePeriodInDays;
uint256 public override lateFeeApr;
// Accounting variables
uint256 public override balance;
uint256 public override interestOwed;
uint256 public override principalOwed;
uint256 public override termEndTime;
uint256 public override nextDueTime;
uint256 public override interestAccruedAsOf;
uint256 public override lastFullPaymentTime;
uint256 public totalInterestAccrued;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
function initialize(
address _config,
address owner,
address _borrower,
uint256 _maxLimit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays
) public initializer {
require(_config != address(0) && owner != address(0) && _borrower != address(0), "Zero address passed in");
__BaseUpgradeablePausable__init(owner);
config = GoldfinchConfig(_config);
borrower = _borrower;
maxLimit = _maxLimit;
interestApr = _interestApr;
paymentPeriodInDays = _paymentPeriodInDays;
termInDays = _termInDays;
lateFeeApr = _lateFeeApr;
principalGracePeriodInDays = _principalGracePeriodInDays;
interestAccruedAsOf = block.timestamp;
// Unlock owner, which is a TranchedPool, for infinite amount
bool success = config.getUSDC().approve(owner, uint256(-1));
require(success, "Failed to approve USDC");
}
function limit() external view override returns (uint256) {
return currentLimit;
}
/**
* @notice Updates the internal accounting to track a drawdown as of current block timestamp.
* Does not move any money
* @param amount The amount in USDC that has been drawndown
*/
function drawdown(uint256 amount) external onlyAdmin {
require(amount.add(balance) <= currentLimit, "Cannot drawdown more than the limit");
require(amount > 0, "Invalid drawdown amount");
uint256 timestamp = currentTime();
if (balance == 0) {
setInterestAccruedAsOf(timestamp);
setLastFullPaymentTime(timestamp);
setTotalInterestAccrued(0);
setTermEndTime(timestamp.add(SECONDS_PER_DAY.mul(termInDays)));
}
(uint256 _interestOwed, uint256 _principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(timestamp);
balance = balance.add(amount);
updateCreditLineAccounting(balance, _interestOwed, _principalOwed);
require(!_isLate(timestamp), "Cannot drawdown when payments are past due");
}
/**
* @notice Migrates to a new goldfinch config address
*/
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
function setLateFeeApr(uint256 newLateFeeApr) external onlyAdmin {
lateFeeApr = newLateFeeApr;
}
function setLimit(uint256 newAmount) external onlyAdmin {
require(newAmount <= maxLimit, "Cannot be more than the max limit");
currentLimit = newAmount;
}
function setMaxLimit(uint256 newAmount) external onlyAdmin {
maxLimit = newAmount;
}
function termStartTime() external view returns (uint256) {
return _termStartTime();
}
function isLate() external view override returns (bool) {
return _isLate(block.timestamp);
}
function withinPrincipalGracePeriod() external view override returns (bool) {
if (termEndTime == 0) {
// Loan hasn't started yet
return true;
}
return block.timestamp < _termStartTime().add(principalGracePeriodInDays.mul(SECONDS_PER_DAY));
}
function setTermEndTime(uint256 newTermEndTime) public onlyAdmin {
termEndTime = newTermEndTime;
}
function setNextDueTime(uint256 newNextDueTime) public onlyAdmin {
nextDueTime = newNextDueTime;
}
function setBalance(uint256 newBalance) public onlyAdmin {
balance = newBalance;
}
function setTotalInterestAccrued(uint256 _totalInterestAccrued) public onlyAdmin {
totalInterestAccrued = _totalInterestAccrued;
}
function setInterestOwed(uint256 newInterestOwed) public onlyAdmin {
interestOwed = newInterestOwed;
}
function setPrincipalOwed(uint256 newPrincipalOwed) public onlyAdmin {
principalOwed = newPrincipalOwed;
}
function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) public onlyAdmin {
interestAccruedAsOf = newInterestAccruedAsOf;
}
function setLastFullPaymentTime(uint256 newLastFullPaymentTime) public onlyAdmin {
lastFullPaymentTime = newLastFullPaymentTime;
}
/**
* @notice Triggers an assessment of the creditline. Any USDC balance available in the creditline is applied
* towards the interest and principal.
* @return Any amount remaining after applying payments towards the interest and principal
* @return Amount applied towards interest
* @return Amount applied towards principal
*/
function assess()
public
onlyAdmin
returns (
uint256,
uint256,
uint256
)
{
// Do not assess until a full period has elapsed or past due
require(balance > 0, "Must have balance to assess credit line");
// Don't assess credit lines early!
if (currentTime() < nextDueTime && !_isLate(currentTime())) {
return (0, 0, 0);
}
uint256 timeToAssess = calculateNextDueTime();
setNextDueTime(timeToAssess);
// We always want to assess for the most recently *past* nextDueTime.
// So if the recalculation above sets the nextDueTime into the future,
// then ensure we pass in the one just before this.
if (timeToAssess > currentTime()) {
uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY);
timeToAssess = timeToAssess.sub(secondsPerPeriod);
}
return handlePayment(getUSDCBalance(address(this)), timeToAssess);
}
function calculateNextDueTime() internal view returns (uint256) {
uint256 newNextDueTime = nextDueTime;
uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY);
uint256 curTimestamp = currentTime();
// You must have just done your first drawdown
if (newNextDueTime == 0 && balance > 0) {
return curTimestamp.add(secondsPerPeriod);
}
// Active loan that has entered a new period, so return the *next* newNextDueTime.
// But never return something after the termEndTime
if (balance > 0 && curTimestamp >= newNextDueTime) {
uint256 secondsToAdvance = (curTimestamp.sub(newNextDueTime).div(secondsPerPeriod)).add(1).mul(secondsPerPeriod);
newNextDueTime = newNextDueTime.add(secondsToAdvance);
return Math.min(newNextDueTime, termEndTime);
}
// You're paid off, or have not taken out a loan yet, so no next due time.
if (balance == 0 && newNextDueTime != 0) {
return 0;
}
// Active loan in current period, where we've already set the newNextDueTime correctly, so should not change.
if (balance > 0 && curTimestamp < newNextDueTime) {
return newNextDueTime;
}
revert("Error: could not calculate next due time.");
}
function currentTime() internal view virtual returns (uint256) {
return block.timestamp;
}
function _isLate(uint256 timestamp) internal view returns (bool) {
uint256 secondsElapsedSinceFullPayment = timestamp.sub(lastFullPaymentTime);
return balance > 0 && secondsElapsedSinceFullPayment > paymentPeriodInDays.mul(SECONDS_PER_DAY);
}
function _termStartTime() internal view returns (uint256) {
return termEndTime.sub(SECONDS_PER_DAY.mul(termInDays));
}
/**
* @notice Applies `amount` of payment for a given credit line. This moves already collected money into the Pool.
* It also updates all the accounting variables. Note that interest is always paid back first, then principal.
* Any extra after paying the minimum will go towards existing principal (reducing the
* effective interest rate). Any extra after the full loan has been paid off will remain in the
* USDC Balance of the creditLine, where it will be automatically used for the next drawdown.
* @param paymentAmount The amount, in USDC atomic units, to be applied
* @param timestamp The timestamp on which accrual calculations should be based. This allows us
* to be precise when we assess a Credit Line
*/
function handlePayment(uint256 paymentAmount, uint256 timestamp)
internal
returns (
uint256,
uint256,
uint256
)
{
(uint256 newInterestOwed, uint256 newPrincipalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(timestamp);
Accountant.PaymentAllocation memory pa = Accountant.allocatePayment(
paymentAmount,
balance,
newInterestOwed,
newPrincipalOwed
);
uint256 newBalance = balance.sub(pa.principalPayment);
// Apply any additional payment towards the balance
newBalance = newBalance.sub(pa.additionalBalancePayment);
uint256 totalPrincipalPayment = balance.sub(newBalance);
uint256 paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment);
updateCreditLineAccounting(
newBalance,
newInterestOwed.sub(pa.interestPayment),
newPrincipalOwed.sub(pa.principalPayment)
);
assert(paymentRemaining.add(pa.interestPayment).add(totalPrincipalPayment) == paymentAmount);
return (paymentRemaining, pa.interestPayment, totalPrincipalPayment);
}
function updateAndGetInterestAndPrincipalOwedAsOf(uint256 timestamp) internal returns (uint256, uint256) {
(uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued(
this,
timestamp,
config.getLatenessGracePeriodInDays()
);
if (interestAccrued > 0) {
// If we've accrued any interest, update interestAccruedAsOf to the time that we've
// calculated interest for. If we've not accrued any interest, then we keep the old value so the next
// time the entire period is taken into account.
setInterestAccruedAsOf(timestamp);
totalInterestAccrued = totalInterestAccrued.add(interestAccrued);
}
return (interestOwed.add(interestAccrued), principalOwed.add(principalAccrued));
}
function updateCreditLineAccounting(
uint256 newBalance,
uint256 newInterestOwed,
uint256 newPrincipalOwed
) internal nonReentrant {
setBalance(newBalance);
setInterestOwed(newInterestOwed);
setPrincipalOwed(newPrincipalOwed);
// This resets lastFullPaymentTime. These conditions assure that they have
// indeed paid off all their interest and they have a real nextDueTime. (ie. creditline isn't pre-drawdown)
uint256 _nextDueTime = nextDueTime;
if (newInterestOwed == 0 && _nextDueTime != 0) {
// If interest was fully paid off, then set the last full payment as the previous due time
uint256 mostRecentLastDueTime;
if (currentTime() < _nextDueTime) {
uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY);
mostRecentLastDueTime = _nextDueTime.sub(secondsPerPeriod);
} else {
mostRecentLastDueTime = _nextDueTime;
}
setLastFullPaymentTime(mostRecentLastDueTime);
}
setNextDueTime(calculateNextDueTime());
}
function getUSDCBalance(address _address) internal view returns (uint256) {
return config.getUSDC().balanceOf(_address);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
// solhint-disable
// Imported from https://github.com/UMAprotocol/protocol/blob/4d1c8cc47a4df5e79f978cb05647a7432e111a3d/packages/core/contracts/common/implementation/FixedPoint.sol
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SignedSafeMath.sol";
/**
* @title Library for fixed point arithmetic on uints
*/
library FixedPoint {
using SafeMath for uint256;
using SignedSafeMath for int256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For unsigned values:
// This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
// --------------------------------------- UNSIGNED -----------------------------------------------------------------------------
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`.
* @param a uint to convert into a FixedPoint.
* @return the converted FixedPoint.
*/
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the minimum of `a` and `b`.
*/
function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the maximum of `a` and `b`.
*/
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.
* @param a a uint256.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/**
* @notice Multiplies two `Unsigned`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a uint256.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a uint256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/**
* @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
uint256 divFloor = aScaled.div(b.rawValue);
uint256 mod = aScaled.mod(b.rawValue);
if (mod != 0) {
return Unsigned(divFloor.add(1));
} else {
return Unsigned(divFloor);
}
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))"
// similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.
// This creates the possibility of overflow if b is very large.
return divCeil(a, fromUnscaledUint(b));
}
/**
* @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return output is `a` to the power of `b`.
*/
function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {
output = fromUnscaledUint(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
// ------------------------------------------------- SIGNED -------------------------------------------------------------
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For signed values:
// This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76.
int256 private constant SFP_SCALING_FACTOR = 10**18;
struct Signed {
int256 rawValue;
}
function fromSigned(Signed memory a) internal pure returns (Unsigned memory) {
require(a.rawValue >= 0, "Negative value provided");
return Unsigned(uint256(a.rawValue));
}
function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) {
require(a.rawValue <= uint256(type(int256).max), "Unsigned too large");
return Signed(int256(a.rawValue));
}
/**
* @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5**18`.
* @param a int to convert into a FixedPoint.Signed.
* @return the converted FixedPoint.Signed.
*/
function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
return Signed(a.mul(SFP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a int256.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the minimum of `a` and `b`.
*/
function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the maximum of `a` and `b`.
*/
function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Signed` to an unscaled int, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, int256 b) internal pure returns (Signed memory) {
return add(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, int256 b) internal pure returns (Signed memory) {
return sub(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(int256 a, Signed memory b) internal pure returns (Signed memory) {
return sub(fromUnscaledInt(a), b);
}
/**
* @notice Multiplies two `Signed`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as an int256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because SFP_SCALING_FACTOR != 0.
return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 mulRaw = a.rawValue.mul(b.rawValue);
int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR;
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = mulRaw % SFP_SCALING_FACTOR;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(mulTowardsZero.add(valueToAdd));
} else {
return Signed(mulTowardsZero);
}
}
/**
* @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Signed(a.rawValue.mul(b));
}
/**
* @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as an int256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a an int256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(int256 a, Signed memory b) internal pure returns (Signed memory) {
return div(fromUnscaledInt(a), b);
}
/**
* @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR);
int256 divTowardsZero = aScaled.div(b.rawValue);
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = aScaled % b.rawValue;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(divTowardsZero.add(valueToAdd));
} else {
return Signed(divTowardsZero);
}
}
/**
* @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))"
// similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed.
// This creates the possibility of overflow if b is very large.
return divAwayFromZero(a, fromUnscaledInt(b));
}
/**
* @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint.Signed.
* @param b a uint256 (negative exponents are not allowed).
* @return output is `a` to the power of `b`.
*/
function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) {
output = fromUnscaledInt(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
pragma solidity ^0.6.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../interfaces/IERC20withDec.sol";
import "../protocol/core/GoldfinchConfig.sol";
import "../protocol/core/ConfigHelper.sol";
import "../protocol/core/TranchedPool.sol";
contract TestTranchedPool is TranchedPool {
function _collectInterestAndPrincipal(
address from,
uint256 interest,
uint256 principal
) public {
collectInterestAndPrincipal(from, interest, principal);
}
function _setSeniorTranchePrincipalDeposited(uint256 principalDeposited) public {
poolSlices[poolSlices.length - 1].seniorTranche.principalDeposited = principalDeposited;
}
function _setLimit(uint256 limit) public {
creditLine.setLimit(limit);
}
function _modifyJuniorTrancheLockedUntil(uint256 lockedUntil) public {
poolSlices[poolSlices.length - 1].juniorTranche.lockedUntil = lockedUntil;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/drafts/IERC20Permit.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../../interfaces/ITranchedPool.sol";
import "../../interfaces/IERC20withDec.sol";
import "../../interfaces/IV2CreditLine.sol";
import "../../interfaces/IPoolTokens.sol";
import "./GoldfinchConfig.sol";
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
import "../../library/SafeERC20Transfer.sol";
import "./TranchingLogic.sol";
contract TranchedPool is BaseUpgradeablePausable, ITranchedPool, SafeERC20Transfer {
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
using TranchingLogic for PoolSlice;
using TranchingLogic for TrancheInfo;
bytes32 public constant LOCKER_ROLE = keccak256("LOCKER_ROLE");
bytes32 public constant SENIOR_ROLE = keccak256("SENIOR_ROLE");
uint256 public constant FP_SCALING_FACTOR = 1e18;
uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;
uint256 public constant ONE_HUNDRED = 100; // Need this because we cannot call .div on a literal 100
uint256 public constant NUM_TRANCHES_PER_SLICE = 2;
uint256 public juniorFeePercent;
bool public drawdownsPaused;
uint256[] public allowedUIDTypes;
uint256 public totalDeployed;
uint256 public fundableAt;
PoolSlice[] public poolSlices;
event DepositMade(address indexed owner, uint256 indexed tranche, uint256 indexed tokenId, uint256 amount);
event WithdrawalMade(
address indexed owner,
uint256 indexed tranche,
uint256 indexed tokenId,
uint256 interestWithdrawn,
uint256 principalWithdrawn
);
event GoldfinchConfigUpdated(address indexed who, address configAddress);
event TranchedPoolAssessed(address indexed pool);
event PaymentApplied(
address indexed payer,
address indexed pool,
uint256 interestAmount,
uint256 principalAmount,
uint256 remainingAmount,
uint256 reserveAmount
);
// Note: This has to exactly match the even in the TranchingLogic library for events to be emitted
// correctly
event SharePriceUpdated(
address indexed pool,
uint256 indexed tranche,
uint256 principalSharePrice,
int256 principalDelta,
uint256 interestSharePrice,
int256 interestDelta
);
event ReserveFundsCollected(address indexed from, uint256 amount);
event CreditLineMigrated(address indexed oldCreditLine, address indexed newCreditLine);
event DrawdownMade(address indexed borrower, uint256 amount);
event DrawdownsPaused(address indexed pool);
event DrawdownsUnpaused(address indexed pool);
event EmergencyShutdown(address indexed pool);
event TrancheLocked(address indexed pool, uint256 trancheId, uint256 lockedUntil);
event SliceCreated(address indexed pool, uint256 sliceId);
function initialize(
address _config,
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays,
uint256 _fundableAt,
uint256[] calldata _allowedUIDTypes
) public override initializer {
require(address(_config) != address(0) && address(_borrower) != address(0), "Config/borrower invalid");
config = GoldfinchConfig(_config);
address owner = config.protocolAdminAddress();
require(owner != address(0), "Owner invalid");
__BaseUpgradeablePausable__init(owner);
_initializeNextSlice(_fundableAt);
createAndSetCreditLine(
_borrower,
_limit,
_interestApr,
_paymentPeriodInDays,
_termInDays,
_lateFeeApr,
_principalGracePeriodInDays
);
createdAt = block.timestamp;
juniorFeePercent = _juniorFeePercent;
if (_allowedUIDTypes.length == 0) {
uint256[1] memory defaultAllowedUIDTypes = [config.getGo().ID_TYPE_0()];
allowedUIDTypes = defaultAllowedUIDTypes;
} else {
allowedUIDTypes = _allowedUIDTypes;
}
_setupRole(LOCKER_ROLE, _borrower);
_setupRole(LOCKER_ROLE, owner);
_setRoleAdmin(LOCKER_ROLE, OWNER_ROLE);
_setRoleAdmin(SENIOR_ROLE, OWNER_ROLE);
// Give the senior pool the ability to deposit into the senior pool
_setupRole(SENIOR_ROLE, address(config.getSeniorPool()));
// Unlock self for infinite amount
bool success = config.getUSDC().approve(address(this), uint256(-1));
require(success, "Failed to approve USDC");
}
function setAllowedUIDTypes(uint256[] calldata ids) public onlyLocker {
require(
poolSlices[0].juniorTranche.principalDeposited == 0 && poolSlices[0].seniorTranche.principalDeposited == 0,
"Must not have balance"
);
allowedUIDTypes = ids;
}
/**
* @notice Deposit a USDC amount into the pool for a tranche. Mints an NFT to the caller representing the position
* @param tranche The number representing the tranche to deposit into
* @param amount The USDC amount to tranfer from the caller to the pool
* @return tokenId The tokenId of the NFT
*/
function deposit(uint256 tranche, uint256 amount)
public
override
nonReentrant
whenNotPaused
returns (uint256 tokenId)
{
TrancheInfo storage trancheInfo = getTrancheInfo(tranche);
require(trancheInfo.lockedUntil == 0, "Tranche locked");
require(amount > 0, "Must deposit > zero");
require(config.getGo().goOnlyIdTypes(msg.sender, allowedUIDTypes), "Address not go-listed");
require(block.timestamp > fundableAt, "Not open for funding");
// senior tranche ids are always odd numbered
if (_isSeniorTrancheId(trancheInfo.id)) {
require(hasRole(SENIOR_ROLE, _msgSender()), "Req SENIOR_ROLE");
}
trancheInfo.principalDeposited = trancheInfo.principalDeposited.add(amount);
IPoolTokens.MintParams memory params = IPoolTokens.MintParams({tranche: tranche, principalAmount: amount});
tokenId = config.getPoolTokens().mint(params, msg.sender);
safeERC20TransferFrom(config.getUSDC(), msg.sender, address(this), amount);
emit DepositMade(msg.sender, tranche, tokenId, amount);
return tokenId;
}
function depositWithPermit(
uint256 tranche,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public override returns (uint256 tokenId) {
IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s);
return deposit(tranche, amount);
}
/**
* @notice Withdraw an already deposited amount if the funds are available
* @param tokenId The NFT representing the position
* @param amount The amount to withdraw (must be <= interest+principal currently available to withdraw)
* @return interestWithdrawn The interest amount that was withdrawn
* @return principalWithdrawn The principal amount that was withdrawn
*/
function withdraw(uint256 tokenId, uint256 amount)
public
override
nonReentrant
whenNotPaused
returns (uint256 interestWithdrawn, uint256 principalWithdrawn)
{
IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId);
TrancheInfo storage trancheInfo = getTrancheInfo(tokenInfo.tranche);
return _withdraw(trancheInfo, tokenInfo, tokenId, amount);
}
/**
* @notice Withdraw from many tokens (that the sender owns) in a single transaction
* @param tokenIds An array of tokens ids representing the position
* @param amounts An array of amounts to withdraw from the corresponding tokenIds
*/
function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) public override {
require(tokenIds.length == amounts.length, "TokensIds and Amounts mismatch");
for (uint256 i = 0; i < amounts.length; i++) {
withdraw(tokenIds[i], amounts[i]);
}
}
/**
* @notice Similar to withdraw but will withdraw all available funds
* @param tokenId The NFT representing the position
* @return interestWithdrawn The interest amount that was withdrawn
* @return principalWithdrawn The principal amount that was withdrawn
*/
function withdrawMax(uint256 tokenId)
external
override
nonReentrant
whenNotPaused
returns (uint256 interestWithdrawn, uint256 principalWithdrawn)
{
IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId);
TrancheInfo storage trancheInfo = getTrancheInfo(tokenInfo.tranche);
(uint256 interestRedeemable, uint256 principalRedeemable) = redeemableInterestAndPrincipal(trancheInfo, tokenInfo);
uint256 amount = interestRedeemable.add(principalRedeemable);
return _withdraw(trancheInfo, tokenInfo, tokenId, amount);
}
/**
* @notice Draws down the funds (and locks the pool) to the borrower address. Can only be called by the borrower
* @param amount The amount to drawdown from the creditline (must be < limit)
*/
function drawdown(uint256 amount) external override onlyLocker whenNotPaused {
require(!drawdownsPaused, "Drawdowns are paused");
if (!locked()) {
// Assumes the senior pool has invested already (saves the borrower a separate transaction to lock the pool)
_lockPool();
}
// Drawdown only draws down from the current slice for simplicity. It's harder to account for how much
// money is available from previous slices since depositors can redeem after unlock.
PoolSlice storage currentSlice = poolSlices[poolSlices.length.sub(1)];
uint256 amountAvailable = sharePriceToUsdc(
currentSlice.juniorTranche.principalSharePrice,
currentSlice.juniorTranche.principalDeposited
);
amountAvailable = amountAvailable.add(
sharePriceToUsdc(currentSlice.seniorTranche.principalSharePrice, currentSlice.seniorTranche.principalDeposited)
);
require(amount <= amountAvailable, "Insufficient funds in slice");
creditLine.drawdown(amount);
// Update the share price to reflect the amount remaining in the pool
uint256 amountRemaining = amountAvailable.sub(amount);
uint256 oldJuniorPrincipalSharePrice = currentSlice.juniorTranche.principalSharePrice;
uint256 oldSeniorPrincipalSharePrice = currentSlice.seniorTranche.principalSharePrice;
currentSlice.juniorTranche.principalSharePrice = currentSlice.juniorTranche.calculateExpectedSharePrice(
amountRemaining,
currentSlice
);
currentSlice.seniorTranche.principalSharePrice = currentSlice.seniorTranche.calculateExpectedSharePrice(
amountRemaining,
currentSlice
);
currentSlice.principalDeployed = currentSlice.principalDeployed.add(amount);
totalDeployed = totalDeployed.add(amount);
address borrower = creditLine.borrower();
safeERC20TransferFrom(config.getUSDC(), address(this), borrower, amount);
emit DrawdownMade(borrower, amount);
emit SharePriceUpdated(
address(this),
currentSlice.juniorTranche.id,
currentSlice.juniorTranche.principalSharePrice,
int256(oldJuniorPrincipalSharePrice.sub(currentSlice.juniorTranche.principalSharePrice)) * -1,
currentSlice.juniorTranche.interestSharePrice,
0
);
emit SharePriceUpdated(
address(this),
currentSlice.seniorTranche.id,
currentSlice.seniorTranche.principalSharePrice,
int256(oldSeniorPrincipalSharePrice.sub(currentSlice.seniorTranche.principalSharePrice)) * -1,
currentSlice.seniorTranche.interestSharePrice,
0
);
}
/**
* @notice Locks the junior tranche, preventing more junior deposits. Gives time for the senior to determine how
* much to invest (ensure leverage ratio cannot change for the period)
*/
function lockJuniorCapital() external override onlyLocker whenNotPaused {
_lockJuniorCapital(poolSlices.length.sub(1));
}
/**
* @notice Locks the pool (locks both senior and junior tranches and starts the drawdown period). Beyond the drawdown
* period, any unused capital is available to withdraw by all depositors
*/
function lockPool() external override onlyLocker whenNotPaused {
_lockPool();
}
function setFundableAt(uint256 newFundableAt) external override onlyLocker {
fundableAt = newFundableAt;
}
function initializeNextSlice(uint256 _fundableAt) external override onlyLocker whenNotPaused {
require(locked(), "Current slice still active");
require(!creditLine.isLate(), "Creditline is late");
require(creditLine.withinPrincipalGracePeriod(), "Beyond principal grace period");
_initializeNextSlice(_fundableAt);
emit SliceCreated(address(this), poolSlices.length.sub(1));
}
/**
* @notice Triggers an assessment of the creditline and the applies the payments according the tranche waterfall
*/
function assess() external override whenNotPaused {
_assess();
}
/**
* @notice Allows repaying the creditline. Collects the USDC amount from the sender and triggers an assess
* @param amount The amount to repay
*/
function pay(uint256 amount) external override whenNotPaused {
require(amount > 0, "Must pay more than zero");
collectPayment(amount);
_assess();
}
/**
* @notice Migrates to a new goldfinch config address
*/
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
creditLine.updateGoldfinchConfig();
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
/**
* @notice Pauses the pool and sweeps any remaining funds to the treasury reserve.
*/
function emergencyShutdown() public onlyAdmin {
if (!paused()) {
pause();
}
IERC20withDec usdc = config.getUSDC();
address reserveAddress = config.reserveAddress();
// Sweep any funds to community reserve
uint256 poolBalance = usdc.balanceOf(address(this));
if (poolBalance > 0) {
safeERC20Transfer(usdc, reserveAddress, poolBalance);
}
uint256 clBalance = usdc.balanceOf(address(creditLine));
if (clBalance > 0) {
safeERC20TransferFrom(usdc, address(creditLine), reserveAddress, clBalance);
}
emit EmergencyShutdown(address(this));
}
/**
* @notice Pauses all drawdowns (but not deposits/withdraws)
*/
function pauseDrawdowns() public onlyAdmin {
drawdownsPaused = true;
emit DrawdownsPaused(address(this));
}
/**
* @notice Unpause drawdowns
*/
function unpauseDrawdowns() public onlyAdmin {
drawdownsPaused = false;
emit DrawdownsUnpaused(address(this));
}
/**
* @notice Migrates the accounting variables from the current creditline to a brand new one
* @param _borrower The borrower address
* @param _maxLimit The new max limit
* @param _interestApr The new interest APR
* @param _paymentPeriodInDays The new payment period in days
* @param _termInDays The new term in days
* @param _lateFeeApr The new late fee APR
*/
function migrateCreditLine(
address _borrower,
uint256 _maxLimit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays
) public onlyAdmin {
require(_borrower != address(0), "Borrower must not be empty");
require(_paymentPeriodInDays != 0, "Payment period invalid");
require(_termInDays != 0, "Term must not be empty");
address originalClAddr = address(creditLine);
createAndSetCreditLine(
_borrower,
_maxLimit,
_interestApr,
_paymentPeriodInDays,
_termInDays,
_lateFeeApr,
_principalGracePeriodInDays
);
address newClAddr = address(creditLine);
TranchingLogic.migrateAccountingVariables(originalClAddr, newClAddr);
TranchingLogic.closeCreditLine(originalClAddr);
address originalBorrower = IV2CreditLine(originalClAddr).borrower();
address newBorrower = IV2CreditLine(newClAddr).borrower();
// Ensure Roles
if (originalBorrower != newBorrower) {
revokeRole(LOCKER_ROLE, originalBorrower);
grantRole(LOCKER_ROLE, newBorrower);
}
// Transfer any funds to new CL
uint256 clBalance = config.getUSDC().balanceOf(originalClAddr);
if (clBalance > 0) {
safeERC20TransferFrom(config.getUSDC(), originalClAddr, newClAddr, clBalance);
}
emit CreditLineMigrated(originalClAddr, newClAddr);
}
/**
* @notice Migrates to a new creditline without copying the accounting variables
*/
function migrateAndSetNewCreditLine(address newCl) public onlyAdmin {
require(newCl != address(0), "Creditline cannot be empty");
address originalClAddr = address(creditLine);
// Transfer any funds to new CL
uint256 clBalance = config.getUSDC().balanceOf(originalClAddr);
if (clBalance > 0) {
safeERC20TransferFrom(config.getUSDC(), originalClAddr, newCl, clBalance);
}
TranchingLogic.closeCreditLine(originalClAddr);
// set new CL
creditLine = IV2CreditLine(newCl);
// sanity check that the new address is in fact a creditline
creditLine.limit();
emit CreditLineMigrated(originalClAddr, address(creditLine));
}
// CreditLine proxy method
function setLimit(uint256 newAmount) external onlyAdmin {
return creditLine.setLimit(newAmount);
}
function setMaxLimit(uint256 newAmount) external onlyAdmin {
return creditLine.setMaxLimit(newAmount);
}
function getTranche(uint256 tranche) public view override returns (TrancheInfo memory) {
return getTrancheInfo(tranche);
}
function numSlices() public view returns (uint256) {
return poolSlices.length;
}
/**
* @notice Converts USDC amounts to share price
* @param amount The USDC amount to convert
* @param totalShares The total shares outstanding
* @return The share price of the input amount
*/
function usdcToSharePrice(uint256 amount, uint256 totalShares) public pure returns (uint256) {
return TranchingLogic.usdcToSharePrice(amount, totalShares);
}
/**
* @notice Converts share price to USDC amounts
* @param sharePrice The share price to convert
* @param totalShares The total shares outstanding
* @return The USDC amount of the input share price
*/
function sharePriceToUsdc(uint256 sharePrice, uint256 totalShares) public pure returns (uint256) {
return TranchingLogic.sharePriceToUsdc(sharePrice, totalShares);
}
/**
* @notice Returns the total junior capital deposited
* @return The total USDC amount deposited into all junior tranches
*/
function totalJuniorDeposits() external view override returns (uint256) {
uint256 total;
for (uint256 i = 0; i < poolSlices.length; i++) {
total = total.add(poolSlices[i].juniorTranche.principalDeposited);
}
return total;
}
/**
* @notice Determines the amount of interest and principal redeemable by a particular tokenId
* @param tokenId The token representing the position
* @return interestRedeemable The interest available to redeem
* @return principalRedeemable The principal available to redeem
*/
function availableToWithdraw(uint256 tokenId)
public
view
override
returns (uint256 interestRedeemable, uint256 principalRedeemable)
{
IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId);
TrancheInfo storage trancheInfo = getTrancheInfo(tokenInfo.tranche);
if (currentTime() > trancheInfo.lockedUntil) {
return redeemableInterestAndPrincipal(trancheInfo, tokenInfo);
} else {
return (0, 0);
}
}
/* Internal functions */
function _withdraw(
TrancheInfo storage trancheInfo,
IPoolTokens.TokenInfo memory tokenInfo,
uint256 tokenId,
uint256 amount
) internal returns (uint256 interestWithdrawn, uint256 principalWithdrawn) {
require(config.getPoolTokens().isApprovedOrOwner(msg.sender, tokenId), "Not token owner");
require(config.getGo().goOnlyIdTypes(msg.sender, allowedUIDTypes), "Address not go-listed");
require(amount > 0, "Must withdraw more than zero");
(uint256 interestRedeemable, uint256 principalRedeemable) = redeemableInterestAndPrincipal(trancheInfo, tokenInfo);
uint256 netRedeemable = interestRedeemable.add(principalRedeemable);
require(amount <= netRedeemable, "Invalid redeem amount");
require(currentTime() > trancheInfo.lockedUntil, "Tranche is locked");
// If the tranche has not been locked, ensure the deposited amount is correct
if (trancheInfo.lockedUntil == 0) {
trancheInfo.principalDeposited = trancheInfo.principalDeposited.sub(amount);
}
uint256 interestToRedeem = Math.min(interestRedeemable, amount);
uint256 principalToRedeem = Math.min(principalRedeemable, amount.sub(interestToRedeem));
config.getPoolTokens().redeem(tokenId, principalToRedeem, interestToRedeem);
safeERC20TransferFrom(config.getUSDC(), address(this), msg.sender, principalToRedeem.add(interestToRedeem));
emit WithdrawalMade(msg.sender, tokenInfo.tranche, tokenId, interestToRedeem, principalToRedeem);
return (interestToRedeem, principalToRedeem);
}
function _isSeniorTrancheId(uint256 trancheId) internal pure returns (bool) {
return trancheId.mod(NUM_TRANCHES_PER_SLICE) == 1;
}
function redeemableInterestAndPrincipal(TrancheInfo storage trancheInfo, IPoolTokens.TokenInfo memory tokenInfo)
internal
view
returns (uint256 interestRedeemable, uint256 principalRedeemable)
{
// This supports withdrawing before or after locking because principal share price starts at 1
// and is set to 0 on lock. Interest share price is always 0 until interest payments come back, when it increases
uint256 maxPrincipalRedeemable = sharePriceToUsdc(trancheInfo.principalSharePrice, tokenInfo.principalAmount);
// The principalAmount is used as the totalShares because we want the interestSharePrice to be expressed as a
// percent of total loan value e.g. if the interest is 10% APR, the interestSharePrice should approach a max of 0.1.
uint256 maxInterestRedeemable = sharePriceToUsdc(trancheInfo.interestSharePrice, tokenInfo.principalAmount);
interestRedeemable = maxInterestRedeemable.sub(tokenInfo.interestRedeemed);
principalRedeemable = maxPrincipalRedeemable.sub(tokenInfo.principalRedeemed);
return (interestRedeemable, principalRedeemable);
}
function _lockJuniorCapital(uint256 sliceId) internal {
require(!locked(), "Pool already locked");
require(poolSlices[sliceId].juniorTranche.lockedUntil == 0, "Junior tranche already locked");
uint256 lockedUntil = currentTime().add(config.getDrawdownPeriodInSeconds());
poolSlices[sliceId].juniorTranche.lockedUntil = lockedUntil;
emit TrancheLocked(address(this), poolSlices[sliceId].juniorTranche.id, lockedUntil);
}
function _lockPool() internal {
uint256 sliceId = poolSlices.length.sub(1);
require(poolSlices[sliceId].juniorTranche.lockedUntil > 0, "Junior tranche must be locked");
// Allow locking the pool only once; do not allow extending the lock of an
// already-locked pool. Otherwise the locker could keep the pool locked
// indefinitely, preventing withdrawals.
require(poolSlices[sliceId].seniorTranche.lockedUntil == 0, "Lock cannot be extended");
uint256 currentTotal = poolSlices[sliceId].juniorTranche.principalDeposited.add(
poolSlices[sliceId].seniorTranche.principalDeposited
);
creditLine.setLimit(Math.min(creditLine.limit().add(currentTotal), creditLine.maxLimit()));
// We start the drawdown period, so backers can withdraw unused capital after borrower draws down
uint256 lockPeriod = config.getDrawdownPeriodInSeconds();
poolSlices[sliceId].seniorTranche.lockedUntil = currentTime().add(lockPeriod);
poolSlices[sliceId].juniorTranche.lockedUntil = currentTime().add(lockPeriod);
emit TrancheLocked(
address(this),
poolSlices[sliceId].seniorTranche.id,
poolSlices[sliceId].seniorTranche.lockedUntil
);
emit TrancheLocked(
address(this),
poolSlices[sliceId].juniorTranche.id,
poolSlices[sliceId].juniorTranche.lockedUntil
);
}
function _initializeNextSlice(uint256 newFundableAt) internal {
uint256 numSlices = poolSlices.length;
require(numSlices < 5, "Cannot exceed 5 slices");
poolSlices.push(
PoolSlice({
seniorTranche: TrancheInfo({
id: numSlices.mul(NUM_TRANCHES_PER_SLICE).add(1),
principalSharePrice: usdcToSharePrice(1, 1),
interestSharePrice: 0,
principalDeposited: 0,
lockedUntil: 0
}),
juniorTranche: TrancheInfo({
id: numSlices.mul(NUM_TRANCHES_PER_SLICE).add(2),
principalSharePrice: usdcToSharePrice(1, 1),
interestSharePrice: 0,
principalDeposited: 0,
lockedUntil: 0
}),
totalInterestAccrued: 0,
principalDeployed: 0
})
);
fundableAt = newFundableAt;
}
function collectInterestAndPrincipal(
address from,
uint256 interest,
uint256 principal
) internal returns (uint256 totalReserveAmount) {
safeERC20TransferFrom(config.getUSDC(), from, address(this), principal.add(interest), "Failed to collect payment");
uint256 reserveFeePercent = ONE_HUNDRED.div(config.getReserveDenominator()); // Convert the denonminator to percent
ApplyResult memory result = TranchingLogic.applyToAllSeniorTranches(
poolSlices,
interest,
principal,
reserveFeePercent,
totalDeployed,
creditLine,
juniorFeePercent
);
totalReserveAmount = result.reserveDeduction.add(
TranchingLogic.applyToAllJuniorTranches(
poolSlices,
result.interestRemaining,
result.principalRemaining,
reserveFeePercent,
totalDeployed,
creditLine
)
);
sendToReserve(totalReserveAmount);
return totalReserveAmount;
}
// If the senior tranche of the current slice is locked, then the pool is not open to any more deposits
// (could throw off leverage ratio)
function locked() internal view returns (bool) {
return poolSlices[poolSlices.length.sub(1)].seniorTranche.lockedUntil > 0;
}
function createAndSetCreditLine(
address _borrower,
uint256 _maxLimit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays
) internal {
address _creditLine = config.getGoldfinchFactory().createCreditLine();
creditLine = IV2CreditLine(_creditLine);
creditLine.initialize(
address(config),
address(this), // Set self as the owner
_borrower,
_maxLimit,
_interestApr,
_paymentPeriodInDays,
_termInDays,
_lateFeeApr,
_principalGracePeriodInDays
);
}
function getTrancheInfo(uint256 trancheId) internal view returns (TrancheInfo storage) {
require(trancheId > 0 && trancheId <= poolSlices.length.mul(NUM_TRANCHES_PER_SLICE), "Unsupported tranche");
uint256 sliceId = ((trancheId.add(trancheId.mod(NUM_TRANCHES_PER_SLICE))).div(NUM_TRANCHES_PER_SLICE)).sub(1);
PoolSlice storage slice = poolSlices[sliceId];
TrancheInfo storage trancheInfo = trancheId.mod(NUM_TRANCHES_PER_SLICE) == 1
? slice.seniorTranche
: slice.juniorTranche;
return trancheInfo;
}
function currentTime() internal view virtual returns (uint256) {
return block.timestamp;
}
function sendToReserve(uint256 amount) internal {
emit ReserveFundsCollected(address(this), amount);
safeERC20TransferFrom(
config.getUSDC(),
address(this),
config.reserveAddress(),
amount,
"Failed to send to reserve"
);
}
function collectPayment(uint256 amount) internal {
safeERC20TransferFrom(config.getUSDC(), msg.sender, address(creditLine), amount, "Failed to collect payment");
}
function _assess() internal {
// We need to make sure the pool is locked before we allocate rewards to ensure it's not
// possible to game rewards by sandwiching an interest payment to an unlocked pool
// It also causes issues trying to allocate payments to an empty slice (divide by zero)
require(locked(), "Pool is not locked");
uint256 interestAccrued = creditLine.totalInterestAccrued();
(uint256 paymentRemaining, uint256 interestPayment, uint256 principalPayment) = creditLine.assess();
interestAccrued = creditLine.totalInterestAccrued().sub(interestAccrued);
// Split the interest accrued proportionally across slices so we know how much interest goes to each slice
// We need this because the slice start at different times, so we cannot retroactively allocate the interest
// linearly
uint256[] memory principalPaymentsPerSlice = new uint256[](poolSlices.length);
for (uint256 i = 0; i < poolSlices.length; i++) {
uint256 interestForSlice = TranchingLogic.scaleByFraction(
interestAccrued,
poolSlices[i].principalDeployed,
totalDeployed
);
principalPaymentsPerSlice[i] = TranchingLogic.scaleByFraction(
principalPayment,
poolSlices[i].principalDeployed,
totalDeployed
);
poolSlices[i].totalInterestAccrued = poolSlices[i].totalInterestAccrued.add(interestForSlice);
}
if (interestPayment > 0 || principalPayment > 0) {
uint256 reserveAmount = collectInterestAndPrincipal(
address(creditLine),
interestPayment,
principalPayment.add(paymentRemaining)
);
for (uint256 i = 0; i < poolSlices.length; i++) {
poolSlices[i].principalDeployed = poolSlices[i].principalDeployed.sub(principalPaymentsPerSlice[i]);
totalDeployed = totalDeployed.sub(principalPaymentsPerSlice[i]);
}
config.getBackerRewards().allocateRewards(interestPayment);
emit PaymentApplied(
creditLine.borrower(),
address(this),
interestPayment,
principalPayment,
paymentRemaining,
reserveAmount
);
}
emit TranchedPoolAssessed(address(this));
}
modifier onlyLocker() {
require(hasRole(LOCKER_ROLE, msg.sender), "Must have locker role");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
/**
* @title Safe ERC20 Transfer
* @notice Reverts when transfer is not successful
* @author Goldfinch
*/
abstract contract SafeERC20Transfer {
function safeERC20Transfer(
IERC20 erc20,
address to,
uint256 amount,
string memory message
) internal {
require(to != address(0), "Can't send to zero address");
bool success = erc20.transfer(to, amount);
require(success, message);
}
function safeERC20Transfer(
IERC20 erc20,
address to,
uint256 amount
) internal {
safeERC20Transfer(erc20, to, amount, "Failed to transfer ERC20");
}
function safeERC20TransferFrom(
IERC20 erc20,
address from,
address to,
uint256 amount,
string memory message
) internal {
require(to != address(0), "Can't send to zero address");
bool success = erc20.transferFrom(from, to, amount);
require(success, message);
}
function safeERC20TransferFrom(
IERC20 erc20,
address from,
address to,
uint256 amount
) internal {
string memory message = "Failed to transfer ERC20";
safeERC20TransferFrom(erc20, from, to, amount, message);
}
function safeERC20Approve(
IERC20 erc20,
address spender,
uint256 allowance,
string memory message
) internal {
bool success = erc20.approve(spender, allowance);
require(success, message);
}
function safeERC20Approve(
IERC20 erc20,
address spender,
uint256 allowance
) internal {
string memory message = "Failed to approve ERC20";
safeERC20Approve(erc20, spender, allowance, message);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../interfaces/IV2CreditLine.sol";
import "../../interfaces/ITranchedPool.sol";
import "../../interfaces/IPoolTokens.sol";
import "../../external/FixedPoint.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/**
* @title TranchingLogic
* @notice Library for handling the payments waterfall
* @author Goldfinch
*/
library TranchingLogic {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
event SharePriceUpdated(
address indexed pool,
uint256 indexed tranche,
uint256 principalSharePrice,
int256 principalDelta,
uint256 interestSharePrice,
int256 interestDelta
);
uint256 public constant FP_SCALING_FACTOR = 1e18;
uint256 public constant ONE_HUNDRED = 100; // Need this because we cannot call .div on a literal 100
function usdcToSharePrice(uint256 amount, uint256 totalShares) public pure returns (uint256) {
return totalShares == 0 ? 0 : amount.mul(FP_SCALING_FACTOR).div(totalShares);
}
function sharePriceToUsdc(uint256 sharePrice, uint256 totalShares) public pure returns (uint256) {
return sharePrice.mul(totalShares).div(FP_SCALING_FACTOR);
}
function redeemableInterestAndPrincipal(
ITranchedPool.TrancheInfo storage trancheInfo,
IPoolTokens.TokenInfo memory tokenInfo
) public view returns (uint256 interestRedeemable, uint256 principalRedeemable) {
// This supports withdrawing before or after locking because principal share price starts at 1
// and is set to 0 on lock. Interest share price is always 0 until interest payments come back, when it increases
uint256 maxPrincipalRedeemable = sharePriceToUsdc(trancheInfo.principalSharePrice, tokenInfo.principalAmount);
// The principalAmount is used as the totalShares because we want the interestSharePrice to be expressed as a
// percent of total loan value e.g. if the interest is 10% APR, the interestSharePrice should approach a max of 0.1.
uint256 maxInterestRedeemable = sharePriceToUsdc(trancheInfo.interestSharePrice, tokenInfo.principalAmount);
interestRedeemable = maxInterestRedeemable.sub(tokenInfo.interestRedeemed);
principalRedeemable = maxPrincipalRedeemable.sub(tokenInfo.principalRedeemed);
return (interestRedeemable, principalRedeemable);
}
function calculateExpectedSharePrice(
ITranchedPool.TrancheInfo memory tranche,
uint256 amount,
ITranchedPool.PoolSlice memory slice
) public pure returns (uint256) {
uint256 sharePrice = usdcToSharePrice(amount, tranche.principalDeposited);
return scaleByPercentOwnership(tranche, sharePrice, slice);
}
function scaleForSlice(
ITranchedPool.PoolSlice memory slice,
uint256 amount,
uint256 totalDeployed
) public pure returns (uint256) {
return scaleByFraction(amount, slice.principalDeployed, totalDeployed);
}
// We need to create this struct so we don't run into a stack too deep error due to too many variables
function getSliceInfo(
ITranchedPool.PoolSlice memory slice,
IV2CreditLine creditLine,
uint256 totalDeployed,
uint256 reserveFeePercent
) public view returns (ITranchedPool.SliceInfo memory) {
(uint256 interestAccrued, uint256 principalAccrued) = getTotalInterestAndPrincipal(
slice,
creditLine,
totalDeployed
);
return
ITranchedPool.SliceInfo({
reserveFeePercent: reserveFeePercent,
interestAccrued: interestAccrued,
principalAccrued: principalAccrued
});
}
function getTotalInterestAndPrincipal(
ITranchedPool.PoolSlice memory slice,
IV2CreditLine creditLine,
uint256 totalDeployed
) public view returns (uint256 interestAccrued, uint256 principalAccrued) {
principalAccrued = creditLine.principalOwed();
// In addition to principal actually owed, we need to account for early principal payments
// If the borrower pays back 5K early on a 10K loan, the actual principal accrued should be
// 5K (balance- deployed) + 0 (principal owed)
principalAccrued = totalDeployed.sub(creditLine.balance()).add(principalAccrued);
// Now we need to scale that correctly for the slice we're interested in
principalAccrued = scaleForSlice(slice, principalAccrued, totalDeployed);
// Finally, we need to account for partial drawdowns. e.g. If 20K was deposited, and only 10K was drawn down,
// Then principal accrued should start at 10K (total deposited - principal deployed), not 0. This is because
// share price starts at 1, and is decremented by what was drawn down.
uint256 totalDeposited = slice.seniorTranche.principalDeposited.add(slice.juniorTranche.principalDeposited);
principalAccrued = totalDeposited.sub(slice.principalDeployed).add(principalAccrued);
return (slice.totalInterestAccrued, principalAccrued);
}
function scaleByFraction(
uint256 amount,
uint256 fraction,
uint256 total
) public pure returns (uint256) {
FixedPoint.Unsigned memory totalAsFixedPoint = FixedPoint.fromUnscaledUint(total);
FixedPoint.Unsigned memory fractionAsFixedPoint = FixedPoint.fromUnscaledUint(fraction);
return fractionAsFixedPoint.div(totalAsFixedPoint).mul(amount).div(FP_SCALING_FACTOR).rawValue;
}
function applyToAllSeniorTranches(
ITranchedPool.PoolSlice[] storage poolSlices,
uint256 interest,
uint256 principal,
uint256 reserveFeePercent,
uint256 totalDeployed,
IV2CreditLine creditLine,
uint256 juniorFeePercent
) public returns (ITranchedPool.ApplyResult memory) {
ITranchedPool.ApplyResult memory seniorApplyResult;
for (uint256 i = 0; i < poolSlices.length; i++) {
ITranchedPool.SliceInfo memory sliceInfo = getSliceInfo(
poolSlices[i],
creditLine,
totalDeployed,
reserveFeePercent
);
// Since slices cannot be created when the loan is late, all interest collected can be assumed to split
// pro-rata across the slices. So we scale the interest and principal to the slice
ITranchedPool.ApplyResult memory applyResult = applyToSeniorTranche(
poolSlices[i],
scaleForSlice(poolSlices[i], interest, totalDeployed),
scaleForSlice(poolSlices[i], principal, totalDeployed),
juniorFeePercent,
sliceInfo
);
emitSharePriceUpdatedEvent(poolSlices[i].seniorTranche, applyResult);
seniorApplyResult.interestRemaining = seniorApplyResult.interestRemaining.add(applyResult.interestRemaining);
seniorApplyResult.principalRemaining = seniorApplyResult.principalRemaining.add(applyResult.principalRemaining);
seniorApplyResult.reserveDeduction = seniorApplyResult.reserveDeduction.add(applyResult.reserveDeduction);
}
return seniorApplyResult;
}
function applyToAllJuniorTranches(
ITranchedPool.PoolSlice[] storage poolSlices,
uint256 interest,
uint256 principal,
uint256 reserveFeePercent,
uint256 totalDeployed,
IV2CreditLine creditLine
) public returns (uint256 totalReserveAmount) {
for (uint256 i = 0; i < poolSlices.length; i++) {
ITranchedPool.SliceInfo memory sliceInfo = getSliceInfo(
poolSlices[i],
creditLine,
totalDeployed,
reserveFeePercent
);
// Any remaining interest and principal is then shared pro-rata with the junior slices
ITranchedPool.ApplyResult memory applyResult = applyToJuniorTranche(
poolSlices[i],
scaleForSlice(poolSlices[i], interest, totalDeployed),
scaleForSlice(poolSlices[i], principal, totalDeployed),
sliceInfo
);
emitSharePriceUpdatedEvent(poolSlices[i].juniorTranche, applyResult);
totalReserveAmount = totalReserveAmount.add(applyResult.reserveDeduction);
}
return totalReserveAmount;
}
function emitSharePriceUpdatedEvent(
ITranchedPool.TrancheInfo memory tranche,
ITranchedPool.ApplyResult memory applyResult
) internal {
emit SharePriceUpdated(
address(this),
tranche.id,
tranche.principalSharePrice,
int256(tranche.principalSharePrice.sub(applyResult.oldPrincipalSharePrice)),
tranche.interestSharePrice,
int256(tranche.interestSharePrice.sub(applyResult.oldInterestSharePrice))
);
}
function applyToSeniorTranche(
ITranchedPool.PoolSlice storage slice,
uint256 interestRemaining,
uint256 principalRemaining,
uint256 juniorFeePercent,
ITranchedPool.SliceInfo memory sliceInfo
) public returns (ITranchedPool.ApplyResult memory) {
// First determine the expected share price for the senior tranche. This is the gross amount the senior
// tranche should receive.
uint256 expectedInterestSharePrice = calculateExpectedSharePrice(
slice.seniorTranche,
sliceInfo.interestAccrued,
slice
);
uint256 expectedPrincipalSharePrice = calculateExpectedSharePrice(
slice.seniorTranche,
sliceInfo.principalAccrued,
slice
);
// Deduct the junior fee and the protocol reserve
uint256 desiredNetInterestSharePrice = scaleByFraction(
expectedInterestSharePrice,
ONE_HUNDRED.sub(juniorFeePercent.add(sliceInfo.reserveFeePercent)),
ONE_HUNDRED
);
// Collect protocol fee interest received (we've subtracted this from the senior portion above)
uint256 reserveDeduction = scaleByFraction(interestRemaining, sliceInfo.reserveFeePercent, ONE_HUNDRED);
interestRemaining = interestRemaining.sub(reserveDeduction);
uint256 oldInterestSharePrice = slice.seniorTranche.interestSharePrice;
uint256 oldPrincipalSharePrice = slice.seniorTranche.principalSharePrice;
// Apply the interest remaining so we get up to the netInterestSharePrice
(interestRemaining, principalRemaining) = applyBySharePrice(
slice.seniorTranche,
interestRemaining,
principalRemaining,
desiredNetInterestSharePrice,
expectedPrincipalSharePrice
);
return
ITranchedPool.ApplyResult({
interestRemaining: interestRemaining,
principalRemaining: principalRemaining,
reserveDeduction: reserveDeduction,
oldInterestSharePrice: oldInterestSharePrice,
oldPrincipalSharePrice: oldPrincipalSharePrice
});
}
function applyToJuniorTranche(
ITranchedPool.PoolSlice storage slice,
uint256 interestRemaining,
uint256 principalRemaining,
ITranchedPool.SliceInfo memory sliceInfo
) public returns (ITranchedPool.ApplyResult memory) {
// Then fill up the junior tranche with all the interest remaining, upto the principal share price
uint256 expectedInterestSharePrice = slice.juniorTranche.interestSharePrice.add(
usdcToSharePrice(interestRemaining, slice.juniorTranche.principalDeposited)
);
uint256 expectedPrincipalSharePrice = calculateExpectedSharePrice(
slice.juniorTranche,
sliceInfo.principalAccrued,
slice
);
uint256 oldInterestSharePrice = slice.juniorTranche.interestSharePrice;
uint256 oldPrincipalSharePrice = slice.juniorTranche.principalSharePrice;
(interestRemaining, principalRemaining) = applyBySharePrice(
slice.juniorTranche,
interestRemaining,
principalRemaining,
expectedInterestSharePrice,
expectedPrincipalSharePrice
);
// All remaining interest and principal is applied towards the junior tranche as interest
interestRemaining = interestRemaining.add(principalRemaining);
// Since any principal remaining is treated as interest (there is "extra" interest to be distributed)
// we need to make sure to collect the protocol fee on the additional interest (we only deducted the
// fee on the original interest portion)
uint256 reserveDeduction = scaleByFraction(principalRemaining, sliceInfo.reserveFeePercent, ONE_HUNDRED);
interestRemaining = interestRemaining.sub(reserveDeduction);
principalRemaining = 0;
(interestRemaining, principalRemaining) = applyByAmount(
slice.juniorTranche,
interestRemaining.add(principalRemaining),
0,
interestRemaining.add(principalRemaining),
0
);
return
ITranchedPool.ApplyResult({
interestRemaining: interestRemaining,
principalRemaining: principalRemaining,
reserveDeduction: reserveDeduction,
oldInterestSharePrice: oldInterestSharePrice,
oldPrincipalSharePrice: oldPrincipalSharePrice
});
}
function applyBySharePrice(
ITranchedPool.TrancheInfo storage tranche,
uint256 interestRemaining,
uint256 principalRemaining,
uint256 desiredInterestSharePrice,
uint256 desiredPrincipalSharePrice
) public returns (uint256, uint256) {
uint256 desiredInterestAmount = desiredAmountFromSharePrice(
desiredInterestSharePrice,
tranche.interestSharePrice,
tranche.principalDeposited
);
uint256 desiredPrincipalAmount = desiredAmountFromSharePrice(
desiredPrincipalSharePrice,
tranche.principalSharePrice,
tranche.principalDeposited
);
return applyByAmount(tranche, interestRemaining, principalRemaining, desiredInterestAmount, desiredPrincipalAmount);
}
function applyByAmount(
ITranchedPool.TrancheInfo storage tranche,
uint256 interestRemaining,
uint256 principalRemaining,
uint256 desiredInterestAmount,
uint256 desiredPrincipalAmount
) public returns (uint256, uint256) {
uint256 totalShares = tranche.principalDeposited;
uint256 newSharePrice;
(interestRemaining, newSharePrice) = applyToSharePrice(
interestRemaining,
tranche.interestSharePrice,
desiredInterestAmount,
totalShares
);
tranche.interestSharePrice = newSharePrice;
(principalRemaining, newSharePrice) = applyToSharePrice(
principalRemaining,
tranche.principalSharePrice,
desiredPrincipalAmount,
totalShares
);
tranche.principalSharePrice = newSharePrice;
return (interestRemaining, principalRemaining);
}
function migrateAccountingVariables(address originalClAddr, address newClAddr) public {
IV2CreditLine originalCl = IV2CreditLine(originalClAddr);
IV2CreditLine newCl = IV2CreditLine(newClAddr);
// Copy over all accounting variables
newCl.setBalance(originalCl.balance());
newCl.setLimit(originalCl.limit());
newCl.setInterestOwed(originalCl.interestOwed());
newCl.setPrincipalOwed(originalCl.principalOwed());
newCl.setTermEndTime(originalCl.termEndTime());
newCl.setNextDueTime(originalCl.nextDueTime());
newCl.setInterestAccruedAsOf(originalCl.interestAccruedAsOf());
newCl.setLastFullPaymentTime(originalCl.lastFullPaymentTime());
newCl.setTotalInterestAccrued(originalCl.totalInterestAccrued());
}
function closeCreditLine(address originalCl) public {
// Close out old CL
IV2CreditLine oldCreditLine = IV2CreditLine(originalCl);
oldCreditLine.setBalance(0);
oldCreditLine.setLimit(0);
oldCreditLine.setMaxLimit(0);
}
function desiredAmountFromSharePrice(
uint256 desiredSharePrice,
uint256 actualSharePrice,
uint256 totalShares
) public pure returns (uint256) {
// If the desired share price is lower, then ignore it, and leave it unchanged
if (desiredSharePrice < actualSharePrice) {
desiredSharePrice = actualSharePrice;
}
uint256 sharePriceDifference = desiredSharePrice.sub(actualSharePrice);
return sharePriceToUsdc(sharePriceDifference, totalShares);
}
function applyToSharePrice(
uint256 amountRemaining,
uint256 currentSharePrice,
uint256 desiredAmount,
uint256 totalShares
) public pure returns (uint256, uint256) {
// If no money left to apply, or don't need any changes, return the original amounts
if (amountRemaining == 0 || desiredAmount == 0) {
return (amountRemaining, currentSharePrice);
}
if (amountRemaining < desiredAmount) {
// We don't have enough money to adjust share price to the desired level. So just use whatever amount is left
desiredAmount = amountRemaining;
}
uint256 sharePriceDifference = usdcToSharePrice(desiredAmount, totalShares);
return (amountRemaining.sub(desiredAmount), currentSharePrice.add(sharePriceDifference));
}
function scaleByPercentOwnership(
ITranchedPool.TrancheInfo memory tranche,
uint256 amount,
ITranchedPool.PoolSlice memory slice
) public pure returns (uint256) {
uint256 totalDeposited = slice.juniorTranche.principalDeposited.add(slice.seniorTranche.principalDeposited);
return scaleByFraction(amount, tranche.principalDeposited, totalDeposited);
}
}
// SPDX-License-Identifier: GPL-3.0-only
// solhint-disable-next-line max-line-length
// Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/MerkleDistributor.sol.
pragma solidity 0.6.12;
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol";
import "../interfaces/IERC20withDec.sol";
import "../interfaces/IMerkleDirectDistributor.sol";
import "../protocol/core/BaseUpgradeablePausable.sol";
contract MerkleDirectDistributor is IMerkleDirectDistributor, BaseUpgradeablePausable {
using SafeERC20 for IERC20withDec;
address public override gfi;
bytes32 public override merkleRoot;
// @dev This is a packed array of booleans.
mapping(uint256 => uint256) private acceptedBitMap;
function initialize(
address owner,
address _gfi,
bytes32 _merkleRoot
) public initializer {
require(owner != address(0), "Owner address cannot be empty");
require(_gfi != address(0), "GFI address cannot be empty");
require(_merkleRoot != 0, "Invalid Merkle root");
__BaseUpgradeablePausable__init(owner);
gfi = _gfi;
merkleRoot = _merkleRoot;
}
function isGrantAccepted(uint256 index) public view override returns (bool) {
uint256 acceptedWordIndex = index / 256;
uint256 acceptedBitIndex = index % 256;
uint256 acceptedWord = acceptedBitMap[acceptedWordIndex];
uint256 mask = (1 << acceptedBitIndex);
return acceptedWord & mask == mask;
}
function _setGrantAccepted(uint256 index) private {
uint256 acceptedWordIndex = index / 256;
uint256 acceptedBitIndex = index % 256;
acceptedBitMap[acceptedWordIndex] = acceptedBitMap[acceptedWordIndex] | (1 << acceptedBitIndex);
}
function acceptGrant(
uint256 index,
uint256 amount,
bytes32[] calldata merkleProof
) external override whenNotPaused {
require(!isGrantAccepted(index), "Grant already accepted");
// Verify the merkle proof.
bytes32 node = keccak256(abi.encodePacked(index, msg.sender, amount));
require(MerkleProof.verify(merkleProof, merkleRoot, node), "Invalid proof");
// Mark it accepted and perform the granting.
_setGrantAccepted(index);
IERC20withDec(gfi).safeTransfer(msg.sender, amount);
emit GrantAccepted(index, msg.sender, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: GPL-3.0-only
// solhint-disable-next-line max-line-length
// Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/interfaces/IMerkleDistributor.sol.
pragma solidity 0.6.12;
/// @notice Enables the transfer of GFI rewards (referred to as a "grant"), if the grant details exist in this
/// contract's Merkle root.
interface IMerkleDirectDistributor {
/// @notice Returns the address of the GFI contract that is the token distributed as rewards by
/// this contract.
function gfi() external view returns (address);
/// @notice Returns the merkle root of the merkle tree containing grant details available to accept.
function merkleRoot() external view returns (bytes32);
/// @notice Returns true if the index has been marked accepted.
function isGrantAccepted(uint256 index) external view returns (bool);
/// @notice Causes the sender to accept the grant consisting of the given details. Reverts if
/// the inputs (which includes who the sender is) are invalid.
function acceptGrant(
uint256 index,
uint256 amount,
bytes32[] calldata merkleProof
) external;
/// @notice This event is triggered whenever a call to #acceptGrant succeeds.
event GrantAccepted(uint256 indexed index, address indexed account, uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/Pool.sol";
import "../protocol/core/BaseUpgradeablePausable.sol";
import "../protocol/core/CreditLine.sol";
contract TestCreditLine is CreditLine {}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/Accountant.sol";
import "../protocol/core/CreditLine.sol";
contract TestAccountant {
function calculateInterestAndPrincipalAccrued(
address creditLineAddress,
uint256 timestamp,
uint256 lateFeeGracePeriod
) public view returns (uint256, uint256) {
CreditLine cl = CreditLine(creditLineAddress);
return Accountant.calculateInterestAndPrincipalAccrued(cl, timestamp, lateFeeGracePeriod);
}
function calculateWritedownFor(
address creditLineAddress,
uint256 blockNumber,
uint256 gracePeriod,
uint256 maxLatePeriods
) public view returns (uint256, uint256) {
CreditLine cl = CreditLine(creditLineAddress);
return Accountant.calculateWritedownFor(cl, blockNumber, gracePeriod, maxLatePeriods);
}
function calculateAmountOwedForOneDay(address creditLineAddress) public view returns (FixedPoint.Unsigned memory) {
CreditLine cl = CreditLine(creditLineAddress);
return Accountant.calculateAmountOwedForOneDay(cl);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/drafts/IERC20Permit.sol";
import "../../interfaces/ISeniorPool.sol";
import "../../interfaces/IPoolTokens.sol";
import "./Accountant.sol";
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
/**
* @title Goldfinch's SeniorPool contract
* @notice Main entry point for senior LPs (a.k.a. capital providers)
* Automatically invests across borrower pools using an adjustable strategy.
* @author Goldfinch
*/
contract SeniorPool is BaseUpgradeablePausable, ISeniorPool {
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
using SafeMath for uint256;
uint256 public compoundBalance;
mapping(ITranchedPool => uint256) public writedowns;
event DepositMade(address indexed capitalProvider, uint256 amount, uint256 shares);
event WithdrawalMade(address indexed capitalProvider, uint256 userAmount, uint256 reserveAmount);
event InterestCollected(address indexed payer, uint256 amount);
event PrincipalCollected(address indexed payer, uint256 amount);
event ReserveFundsCollected(address indexed user, uint256 amount);
event PrincipalWrittenDown(address indexed tranchedPool, int256 amount);
event InvestmentMadeInSenior(address indexed tranchedPool, uint256 amount);
event InvestmentMadeInJunior(address indexed tranchedPool, uint256 amount);
event GoldfinchConfigUpdated(address indexed who, address configAddress);
function initialize(address owner, GoldfinchConfig _config) public initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = _config;
// Initialize sharePrice to be identical to the legacy pool. This is in the initializer
// because it must only ever happen once.
sharePrice = config.getPool().sharePrice();
totalLoansOutstanding = config.getCreditDesk().totalLoansOutstanding();
totalWritedowns = config.getCreditDesk().totalWritedowns();
IERC20withDec usdc = config.getUSDC();
// Sanity check the address
usdc.totalSupply();
bool success = usdc.approve(address(this), uint256(-1));
require(success, "Failed to approve USDC");
}
/**
* @notice Deposits `amount` USDC from msg.sender into the SeniorPool, and grants you the
* equivalent value of FIDU tokens
* @param amount The amount of USDC to deposit
*/
function deposit(uint256 amount) public override whenNotPaused nonReentrant returns (uint256 depositShares) {
require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed");
require(amount > 0, "Must deposit more than zero");
// Check if the amount of new shares to be added is within limits
depositShares = getNumShares(amount);
uint256 potentialNewTotalShares = totalShares().add(depositShares);
require(sharesWithinLimit(potentialNewTotalShares), "Deposit would put the senior pool over the total limit.");
emit DepositMade(msg.sender, amount, depositShares);
bool success = doUSDCTransfer(msg.sender, address(this), amount);
require(success, "Failed to transfer for deposit");
config.getFidu().mintTo(msg.sender, depositShares);
return depositShares;
}
/**
* @notice Identical to deposit, except it allows for a passed up signature to permit
* the Senior Pool to move funds on behalf of the user, all within one transaction.
* @param amount The amount of USDC to deposit
* @param v secp256k1 signature component
* @param r secp256k1 signature component
* @param s secp256k1 signature component
*/
function depositWithPermit(
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public override returns (uint256 depositShares) {
IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s);
return deposit(amount);
}
/**
* @notice Withdraws USDC from the SeniorPool to msg.sender, and burns the equivalent value of FIDU tokens
* @param usdcAmount The amount of USDC to withdraw
*/
function withdraw(uint256 usdcAmount) external override whenNotPaused nonReentrant returns (uint256 amount) {
require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed");
require(usdcAmount > 0, "Must withdraw more than zero");
// This MUST happen before calculating withdrawShares, otherwise the share price
// changes between calculation and burning of Fidu, which creates a asset/liability mismatch
if (compoundBalance > 0) {
_sweepFromCompound();
}
uint256 withdrawShares = getNumShares(usdcAmount);
return _withdraw(usdcAmount, withdrawShares);
}
/**
* @notice Withdraws USDC (denominated in FIDU terms) from the SeniorPool to msg.sender
* @param fiduAmount The amount of USDC to withdraw in terms of FIDU shares
*/
function withdrawInFidu(uint256 fiduAmount) external override whenNotPaused nonReentrant returns (uint256 amount) {
require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed");
require(fiduAmount > 0, "Must withdraw more than zero");
// This MUST happen before calculating withdrawShares, otherwise the share price
// changes between calculation and burning of Fidu, which creates a asset/liability mismatch
if (compoundBalance > 0) {
_sweepFromCompound();
}
uint256 usdcAmount = getUSDCAmountFromShares(fiduAmount);
uint256 withdrawShares = fiduAmount;
return _withdraw(usdcAmount, withdrawShares);
}
/**
* @notice Migrates to a new goldfinch config address
*/
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
/**
* @notice Moves any USDC still in the SeniorPool to Compound, and tracks the amount internally.
* This is done to earn interest on latent funds until we have other borrowers who can use it.
*
* Requirements:
* - The caller must be an admin.
*/
function sweepToCompound() public override onlyAdmin whenNotPaused {
IERC20 usdc = config.getUSDC();
uint256 usdcBalance = usdc.balanceOf(address(this));
ICUSDCContract cUSDC = config.getCUSDCContract();
// Approve compound to the exact amount
bool success = usdc.approve(address(cUSDC), usdcBalance);
require(success, "Failed to approve USDC for compound");
sweepToCompound(cUSDC, usdcBalance);
// Remove compound approval to be extra safe
success = config.getUSDC().approve(address(cUSDC), 0);
require(success, "Failed to approve USDC for compound");
}
/**
* @notice Moves any USDC from Compound back to the SeniorPool, and recognizes interest earned.
* This is done automatically on drawdown or withdraw, but can be called manually if necessary.
*
* Requirements:
* - The caller must be an admin.
*/
function sweepFromCompound() public override onlyAdmin whenNotPaused {
_sweepFromCompound();
}
/**
* @notice Invest in an ITranchedPool's senior tranche using the senior pool's strategy
* @param pool An ITranchedPool whose senior tranche should be considered for investment
*/
function invest(ITranchedPool pool) public override whenNotPaused nonReentrant {
require(validPool(pool), "Pool must be valid");
if (compoundBalance > 0) {
_sweepFromCompound();
}
ISeniorPoolStrategy strategy = config.getSeniorPoolStrategy();
uint256 amount = strategy.invest(this, pool);
require(amount > 0, "Investment amount must be positive");
approvePool(pool, amount);
pool.deposit(uint256(ITranchedPool.Tranches.Senior), amount);
emit InvestmentMadeInSenior(address(pool), amount);
totalLoansOutstanding = totalLoansOutstanding.add(amount);
}
function estimateInvestment(ITranchedPool pool) public view override returns (uint256) {
require(validPool(pool), "Pool must be valid");
ISeniorPoolStrategy strategy = config.getSeniorPoolStrategy();
return strategy.estimateInvestment(this, pool);
}
/**
* @notice Redeem interest and/or principal from an ITranchedPool investment
* @param tokenId the ID of an IPoolTokens token to be redeemed
*/
function redeem(uint256 tokenId) public override whenNotPaused nonReentrant {
IPoolTokens poolTokens = config.getPoolTokens();
IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);
ITranchedPool pool = ITranchedPool(tokenInfo.pool);
(uint256 interestRedeemed, uint256 principalRedeemed) = pool.withdrawMax(tokenId);
_collectInterestAndPrincipal(address(pool), interestRedeemed, principalRedeemed);
}
/**
* @notice Write down an ITranchedPool investment. This will adjust the senior pool's share price
* down if we're considering the investment a loss, or up if the borrower has subsequently
* made repayments that restore confidence that the full loan will be repaid.
* @param tokenId the ID of an IPoolTokens token to be considered for writedown
*/
function writedown(uint256 tokenId) public override whenNotPaused nonReentrant {
IPoolTokens poolTokens = config.getPoolTokens();
require(address(this) == poolTokens.ownerOf(tokenId), "Only tokens owned by the senior pool can be written down");
IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);
ITranchedPool pool = ITranchedPool(tokenInfo.pool);
require(validPool(pool), "Pool must be valid");
uint256 principalRemaining = tokenInfo.principalAmount.sub(tokenInfo.principalRedeemed);
(uint256 writedownPercent, uint256 writedownAmount) = _calculateWritedown(pool, principalRemaining);
uint256 prevWritedownAmount = writedowns[pool];
if (writedownPercent == 0 && prevWritedownAmount == 0) {
return;
}
int256 writedownDelta = int256(prevWritedownAmount) - int256(writedownAmount);
writedowns[pool] = writedownAmount;
distributeLosses(writedownDelta);
if (writedownDelta > 0) {
// If writedownDelta is positive, that means we got money back. So subtract from totalWritedowns.
totalWritedowns = totalWritedowns.sub(uint256(writedownDelta));
} else {
totalWritedowns = totalWritedowns.add(uint256(writedownDelta * -1));
}
emit PrincipalWrittenDown(address(pool), writedownDelta);
}
/**
* @notice Calculates the writedown amount for a particular pool position
* @param tokenId The token reprsenting the position
* @return The amount in dollars the principal should be written down by
*/
function calculateWritedown(uint256 tokenId) public view override returns (uint256) {
IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId);
ITranchedPool pool = ITranchedPool(tokenInfo.pool);
uint256 principalRemaining = tokenInfo.principalAmount.sub(tokenInfo.principalRedeemed);
(, uint256 writedownAmount) = _calculateWritedown(pool, principalRemaining);
return writedownAmount;
}
/**
* @notice Returns the net assests controlled by and owed to the pool
*/
function assets() public view override returns (uint256) {
return
compoundBalance.add(config.getUSDC().balanceOf(address(this))).add(totalLoansOutstanding).sub(totalWritedowns);
}
/**
* @notice Converts and USDC amount to FIDU amount
* @param amount USDC amount to convert to FIDU
*/
function getNumShares(uint256 amount) public view override returns (uint256) {
return usdcToFidu(amount).mul(fiduMantissa()).div(sharePrice);
}
/* Internal Functions */
function _calculateWritedown(ITranchedPool pool, uint256 principal)
internal
view
returns (uint256 writedownPercent, uint256 writedownAmount)
{
return
Accountant.calculateWritedownForPrincipal(
pool.creditLine(),
principal,
currentTime(),
config.getLatenessGracePeriodInDays(),
config.getLatenessMaxDays()
);
}
function currentTime() internal view virtual returns (uint256) {
return block.timestamp;
}
function distributeLosses(int256 writedownDelta) internal {
if (writedownDelta > 0) {
uint256 delta = usdcToSharePrice(uint256(writedownDelta));
sharePrice = sharePrice.add(delta);
} else {
// If delta is negative, convert to positive uint, and sub from sharePrice
uint256 delta = usdcToSharePrice(uint256(writedownDelta * -1));
sharePrice = sharePrice.sub(delta);
}
}
function fiduMantissa() internal pure returns (uint256) {
return uint256(10)**uint256(18);
}
function usdcMantissa() internal pure returns (uint256) {
return uint256(10)**uint256(6);
}
function usdcToFidu(uint256 amount) internal pure returns (uint256) {
return amount.mul(fiduMantissa()).div(usdcMantissa());
}
function fiduToUSDC(uint256 amount) internal pure returns (uint256) {
return amount.div(fiduMantissa().div(usdcMantissa()));
}
function getUSDCAmountFromShares(uint256 fiduAmount) internal view returns (uint256) {
return fiduToUSDC(fiduAmount.mul(sharePrice).div(fiduMantissa()));
}
function sharesWithinLimit(uint256 _totalShares) internal view returns (bool) {
return
_totalShares.mul(sharePrice).div(fiduMantissa()) <=
usdcToFidu(config.getNumber(uint256(ConfigOptions.Numbers.TotalFundsLimit)));
}
function doUSDCTransfer(
address from,
address to,
uint256 amount
) internal returns (bool) {
require(to != address(0), "Can't send to zero address");
IERC20withDec usdc = config.getUSDC();
return usdc.transferFrom(from, to, amount);
}
function _withdraw(uint256 usdcAmount, uint256 withdrawShares) internal returns (uint256 userAmount) {
IFidu fidu = config.getFidu();
// Determine current shares the address has and the shares requested to withdraw
uint256 currentShares = fidu.balanceOf(msg.sender);
// Ensure the address has enough value in the pool
require(withdrawShares <= currentShares, "Amount requested is greater than what this address owns");
uint256 reserveAmount = usdcAmount.div(config.getWithdrawFeeDenominator());
userAmount = usdcAmount.sub(reserveAmount);
emit WithdrawalMade(msg.sender, userAmount, reserveAmount);
// Send the amounts
bool success = doUSDCTransfer(address(this), msg.sender, userAmount);
require(success, "Failed to transfer for withdraw");
sendToReserve(reserveAmount, msg.sender);
// Burn the shares
fidu.burnFrom(msg.sender, withdrawShares);
return userAmount;
}
function sweepToCompound(ICUSDCContract cUSDC, uint256 usdcAmount) internal {
// Our current design requires we re-normalize by withdrawing everything and recognizing interest gains
// before we can add additional capital to Compound
require(compoundBalance == 0, "Cannot sweep when we already have a compound balance");
require(usdcAmount != 0, "Amount to sweep cannot be zero");
uint256 error = cUSDC.mint(usdcAmount);
require(error == 0, "Sweep to compound failed");
compoundBalance = usdcAmount;
}
function _sweepFromCompound() internal {
ICUSDCContract cUSDC = config.getCUSDCContract();
sweepFromCompound(cUSDC, cUSDC.balanceOf(address(this)));
}
function sweepFromCompound(ICUSDCContract cUSDC, uint256 cUSDCAmount) internal {
uint256 cBalance = compoundBalance;
require(cBalance != 0, "No funds on compound");
require(cUSDCAmount != 0, "Amount to sweep cannot be zero");
IERC20 usdc = config.getUSDC();
uint256 preRedeemUSDCBalance = usdc.balanceOf(address(this));
uint256 cUSDCExchangeRate = cUSDC.exchangeRateCurrent();
uint256 redeemedUSDC = cUSDCToUSDC(cUSDCExchangeRate, cUSDCAmount);
uint256 error = cUSDC.redeem(cUSDCAmount);
uint256 postRedeemUSDCBalance = usdc.balanceOf(address(this));
require(error == 0, "Sweep from compound failed");
require(postRedeemUSDCBalance.sub(preRedeemUSDCBalance) == redeemedUSDC, "Unexpected redeem amount");
uint256 interestAccrued = redeemedUSDC.sub(cBalance);
uint256 reserveAmount = interestAccrued.div(config.getReserveDenominator());
uint256 poolAmount = interestAccrued.sub(reserveAmount);
_collectInterestAndPrincipal(address(this), poolAmount, 0);
if (reserveAmount > 0) {
sendToReserve(reserveAmount, address(cUSDC));
}
compoundBalance = 0;
}
function cUSDCToUSDC(uint256 exchangeRate, uint256 amount) internal pure returns (uint256) {
// See https://compound.finance/docs#protocol-math
// But note, the docs and reality do not agree. Docs imply that that exchange rate is
// scaled by 1e18, but tests and mainnet forking make it appear to be scaled by 1e16
// 1e16 is also what Sheraz at Certik said.
uint256 usdcDecimals = 6;
uint256 cUSDCDecimals = 8;
// We multiply in the following order, for the following reasons...
// Amount in cToken (1e8)
// Amount in USDC (but scaled by 1e16, cause that's what exchange rate decimals are)
// Downscale to cToken decimals (1e8)
// Downscale from cToken to USDC decimals (8 to 6)
return amount.mul(exchangeRate).div(10**(18 + usdcDecimals - cUSDCDecimals)).div(10**2);
}
function _collectInterestAndPrincipal(
address from,
uint256 interest,
uint256 principal
) internal {
uint256 increment = usdcToSharePrice(interest);
sharePrice = sharePrice.add(increment);
if (interest > 0) {
emit InterestCollected(from, interest);
}
if (principal > 0) {
emit PrincipalCollected(from, principal);
totalLoansOutstanding = totalLoansOutstanding.sub(principal);
}
}
function sendToReserve(uint256 amount, address userForEvent) internal {
emit ReserveFundsCollected(userForEvent, amount);
bool success = doUSDCTransfer(address(this), config.reserveAddress(), amount);
require(success, "Reserve transfer was not successful");
}
function usdcToSharePrice(uint256 usdcAmount) internal view returns (uint256) {
return usdcToFidu(usdcAmount).mul(fiduMantissa()).div(totalShares());
}
function totalShares() internal view returns (uint256) {
return config.getFidu().totalSupply();
}
function validPool(ITranchedPool pool) internal view returns (bool) {
return config.getPoolTokens().validPool(address(pool));
}
function approvePool(ITranchedPool pool, uint256 allowance) internal {
IERC20withDec usdc = config.getUSDC();
bool success = usdc.approve(address(pool), allowance);
require(success, "Failed to approve USDC");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/SeniorPool.sol";
contract TestSeniorPool is SeniorPool {
function _getNumShares(uint256 amount) public view returns (uint256) {
return getNumShares(amount);
}
function _usdcMantissa() public pure returns (uint256) {
return usdcMantissa();
}
function _fiduMantissa() public pure returns (uint256) {
return fiduMantissa();
}
function _usdcToFidu(uint256 amount) public pure returns (uint256) {
return usdcToFidu(amount);
}
function _setSharePrice(uint256 newSharePrice) public returns (uint256) {
sharePrice = newSharePrice;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "../external/ERC721PresetMinterPauserAutoId.sol";
import "../interfaces/IERC20withDec.sol";
import "../interfaces/ICommunityRewards.sol";
import "../protocol/core/GoldfinchConfig.sol";
import "../protocol/core/ConfigHelper.sol";
import "../library/CommunityRewardsVesting.sol";
contract CommunityRewards is ICommunityRewards, ERC721PresetMinterPauserAutoIdUpgradeSafe, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20withDec;
using ConfigHelper for GoldfinchConfig;
using CommunityRewardsVesting for CommunityRewardsVesting.Rewards;
/* ========== EVENTS ========== */
event GoldfinchConfigUpdated(address indexed who, address configAddress);
/* ========== STATE VARIABLES ========== */
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
bytes32 public constant DISTRIBUTOR_ROLE = keccak256("DISTRIBUTOR_ROLE");
GoldfinchConfig public config;
/// @notice Total rewards available for granting, denominated in `rewardsToken()`
uint256 public rewardsAvailable;
/// @notice Token launch time in seconds. This is used in vesting.
uint256 public tokenLaunchTimeInSeconds;
/// @dev NFT tokenId => rewards grant
mapping(uint256 => CommunityRewardsVesting.Rewards) public grants;
// solhint-disable-next-line func-name-mixedcase
function __initialize__(
address owner,
GoldfinchConfig _config,
uint256 _tokenLaunchTimeInSeconds
) external initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained("Goldfinch V2 Community Rewards Tokens", "GFI-V2-CR");
__ERC721Pausable_init_unchained();
__AccessControl_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
_setupRole(OWNER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
_setupRole(DISTRIBUTOR_ROLE, owner);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(DISTRIBUTOR_ROLE, OWNER_ROLE);
tokenLaunchTimeInSeconds = _tokenLaunchTimeInSeconds;
config = _config;
}
/* ========== VIEWS ========== */
/// @notice The token being disbursed as rewards
function rewardsToken() public view override returns (IERC20withDec) {
return config.getGFI();
}
/// @notice Returns the rewards claimable by a given grant token, taking into
/// account vesting schedule.
/// @return rewards Amount of rewards denominated in `rewardsToken()`
function claimableRewards(uint256 tokenId) public view override returns (uint256 rewards) {
return grants[tokenId].claimable();
}
/// @notice Returns the rewards that will have vested for some grant with the given params.
/// @return rewards Amount of rewards denominated in `rewardsToken()`
function totalVestedAt(
uint256 start,
uint256 end,
uint256 granted,
uint256 cliffLength,
uint256 vestingInterval,
uint256 revokedAt,
uint256 time
) external pure override returns (uint256 rewards) {
return CommunityRewardsVesting.getTotalVestedAt(start, end, granted, cliffLength, vestingInterval, revokedAt, time);
}
/* ========== MUTATIVE, ADMIN-ONLY FUNCTIONS ========== */
/// @notice Transfer rewards from msg.sender, to be used for reward distribution
function loadRewards(uint256 rewards) external override onlyAdmin {
require(rewards > 0, "Cannot load 0 rewards");
rewardsAvailable = rewardsAvailable.add(rewards);
rewardsToken().safeTransferFrom(msg.sender, address(this), rewards);
emit RewardAdded(rewards);
}
/// @notice Revokes rewards that have not yet vested, for a grant. The unvested rewards are
/// now considered available for allocation in another grant.
/// @param tokenId The tokenId corresponding to the grant whose unvested rewards to revoke.
function revokeGrant(uint256 tokenId) external override whenNotPaused onlyAdmin {
CommunityRewardsVesting.Rewards storage grant = grants[tokenId];
require(grant.totalGranted > 0, "Grant not defined for token id");
require(grant.revokedAt == 0, "Grant has already been revoked");
uint256 totalUnvested = grant.totalUnvestedAt(block.timestamp);
require(totalUnvested > 0, "Grant has fully vested");
rewardsAvailable = rewardsAvailable.add(totalUnvested);
grant.revokedAt = block.timestamp;
emit GrantRevoked(tokenId, totalUnvested);
}
function setTokenLaunchTimeInSeconds(uint256 _tokenLaunchTimeInSeconds) external onlyAdmin {
tokenLaunchTimeInSeconds = _tokenLaunchTimeInSeconds;
}
/// @notice updates current config
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(_msgSender(), address(config));
}
/* ========== MUTATIVE, NON-ADMIN-ONLY FUNCTIONS ========== */
/// @notice Grant rewards to a recipient. The recipient address receives an
/// an NFT representing their rewards grant. They can present the NFT to `getReward()`
/// to claim their rewards. Rewards vest over a schedule.
/// @param recipient The recipient of the grant.
/// @param amount The amount of `rewardsToken()` to grant.
/// @param vestingLength The duration (in seconds) over which the grant vests.
/// @param cliffLength The duration (in seconds) from the start of the grant, before which has elapsed
/// the vested amount remains 0.
/// @param vestingInterval The interval (in seconds) at which vesting occurs. Must be a factor of `vestingLength`.
function grant(
address recipient,
uint256 amount,
uint256 vestingLength,
uint256 cliffLength,
uint256 vestingInterval
) external override nonReentrant whenNotPaused onlyDistributor returns (uint256 tokenId) {
return _grant(recipient, amount, vestingLength, cliffLength, vestingInterval);
}
function _grant(
address recipient,
uint256 amount,
uint256 vestingLength,
uint256 cliffLength,
uint256 vestingInterval
) internal returns (uint256 tokenId) {
require(amount > 0, "Cannot grant 0 amount");
require(cliffLength <= vestingLength, "Cliff length cannot exceed vesting length");
require(vestingLength.mod(vestingInterval) == 0, "Vesting interval must be a factor of vesting length");
require(amount <= rewardsAvailable, "Cannot grant amount due to insufficient funds");
rewardsAvailable = rewardsAvailable.sub(amount);
_tokenIdTracker.increment();
tokenId = _tokenIdTracker.current();
grants[tokenId] = CommunityRewardsVesting.Rewards({
totalGranted: amount,
totalClaimed: 0,
startTime: tokenLaunchTimeInSeconds,
endTime: tokenLaunchTimeInSeconds.add(vestingLength),
cliffLength: cliffLength,
vestingInterval: vestingInterval,
revokedAt: 0
});
_mint(recipient, tokenId);
emit Granted(recipient, tokenId, amount, vestingLength, cliffLength, vestingInterval);
return tokenId;
}
/// @notice Claim rewards for a given grant
/// @param tokenId A grant token ID
function getReward(uint256 tokenId) external override nonReentrant whenNotPaused {
require(ownerOf(tokenId) == msg.sender, "access denied");
uint256 reward = claimableRewards(tokenId);
if (reward > 0) {
grants[tokenId].claim(reward);
rewardsToken().safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, tokenId, reward);
}
}
/* ========== MODIFIERS ========== */
function isAdmin() public view returns (bool) {
return hasRole(OWNER_ROLE, _msgSender());
}
modifier onlyAdmin() {
require(isAdmin(), "Must have admin role to perform this action");
_;
}
function isDistributor() public view returns (bool) {
return hasRole(DISTRIBUTOR_ROLE, _msgSender());
}
modifier onlyDistributor() {
require(isDistributor(), "Must have distributor role to perform this action");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol";
import "../interfaces/IERC20withDec.sol";
interface ICommunityRewards is IERC721 {
function rewardsToken() external view returns (IERC20withDec);
function claimableRewards(uint256 tokenId) external view returns (uint256 rewards);
function totalVestedAt(
uint256 start,
uint256 end,
uint256 granted,
uint256 cliffLength,
uint256 vestingInterval,
uint256 revokedAt,
uint256 time
) external pure returns (uint256 rewards);
function grant(
address recipient,
uint256 amount,
uint256 vestingLength,
uint256 cliffLength,
uint256 vestingInterval
) external returns (uint256 tokenId);
function loadRewards(uint256 rewards) external;
function revokeGrant(uint256 tokenId) external;
function getReward(uint256 tokenId) external;
event RewardAdded(uint256 reward);
event Granted(
address indexed user,
uint256 indexed tokenId,
uint256 amount,
uint256 vestingLength,
uint256 cliffLength,
uint256 vestingInterval
);
event GrantRevoked(uint256 indexed tokenId, uint256 totalUnvested);
event RewardPaid(address indexed user, uint256 indexed tokenId, uint256 reward);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
library CommunityRewardsVesting {
using SafeMath for uint256;
using CommunityRewardsVesting for Rewards;
/// @dev All time values in the Rewards struct (i.e. `startTime`, `endTime`,
/// `cliffLength`, `vestingInterval`, `revokedAt`) use the same units: seconds. All timestamp
/// values (i.e. `startTime`, `endTime`, `revokedAt`) are seconds since the unix epoch.
/// @dev `cliffLength` is the duration from the start of the grant, before which has elapsed
/// the vested amount remains 0.
/// @dev `vestingInterval` is the interval at which vesting occurs. For rewards to have
/// vested fully only at `endTime`, `vestingInterval` must be a factor of
/// `endTime.sub(startTime)`. If `vestingInterval` is not thusly a factor, the calculation
/// of `totalVestedAt()` would calculate rewards to have fully vested as of the time of the
/// last whole `vestingInterval`'s elapsing before `endTime`.
struct Rewards {
uint256 totalGranted;
uint256 totalClaimed;
uint256 startTime;
uint256 endTime;
uint256 cliffLength;
uint256 vestingInterval;
uint256 revokedAt;
}
function claim(Rewards storage rewards, uint256 reward) internal {
rewards.totalClaimed = rewards.totalClaimed.add(reward);
}
function claimable(Rewards storage rewards) internal view returns (uint256) {
return claimable(rewards, block.timestamp);
}
function claimable(Rewards storage rewards, uint256 time) internal view returns (uint256) {
return rewards.totalVestedAt(time).sub(rewards.totalClaimed);
}
function totalUnvestedAt(Rewards storage rewards, uint256 time) internal view returns (uint256) {
return rewards.totalGranted.sub(rewards.totalVestedAt(time));
}
function totalVestedAt(Rewards storage rewards, uint256 time) internal view returns (uint256) {
return
getTotalVestedAt(
rewards.startTime,
rewards.endTime,
rewards.totalGranted,
rewards.cliffLength,
rewards.vestingInterval,
rewards.revokedAt,
time
);
}
function getTotalVestedAt(
uint256 start,
uint256 end,
uint256 granted,
uint256 cliffLength,
uint256 vestingInterval,
uint256 revokedAt,
uint256 time
) internal pure returns (uint256) {
if (time < start.add(cliffLength)) {
return 0;
}
if (end <= start) {
return granted;
}
uint256 elapsedVestingTimestamp = revokedAt > 0 ? Math.min(revokedAt, time) : time;
uint256 elapsedVestingUnits = (elapsedVestingTimestamp.sub(start)).div(vestingInterval);
uint256 totalVestingUnits = (end.sub(start)).div(vestingInterval);
return Math.min(granted.mul(elapsedVestingUnits).div(totalVestingUnits), granted);
}
}
// SPDX-License-Identifier: GPL-3.0-only
// solhint-disable-next-line max-line-length
// Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/MerkleDistributor.sol.
pragma solidity 0.6.12;
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
import "../interfaces/ICommunityRewards.sol";
import "../interfaces/IMerkleDistributor.sol";
contract MerkleDistributor is IMerkleDistributor {
address public immutable override communityRewards;
bytes32 public immutable override merkleRoot;
// @dev This is a packed array of booleans.
mapping(uint256 => uint256) private acceptedBitMap;
constructor(address communityRewards_, bytes32 merkleRoot_) public {
require(communityRewards_ != address(0), "Cannot use the null address");
require(merkleRoot_ != 0, "Invalid merkle root provided");
communityRewards = communityRewards_;
merkleRoot = merkleRoot_;
}
function isGrantAccepted(uint256 index) public view override returns (bool) {
uint256 acceptedWordIndex = index / 256;
uint256 acceptedBitIndex = index % 256;
uint256 acceptedWord = acceptedBitMap[acceptedWordIndex];
uint256 mask = (1 << acceptedBitIndex);
return acceptedWord & mask == mask;
}
function _setGrantAccepted(uint256 index) private {
uint256 acceptedWordIndex = index / 256;
uint256 acceptedBitIndex = index % 256;
acceptedBitMap[acceptedWordIndex] = acceptedBitMap[acceptedWordIndex] | (1 << acceptedBitIndex);
}
function acceptGrant(
uint256 index,
uint256 amount,
uint256 vestingLength,
uint256 cliffLength,
uint256 vestingInterval,
bytes32[] calldata merkleProof
) external override {
require(!isGrantAccepted(index), "Grant already accepted");
// Verify the merkle proof.
//
/// @dev Per the Warning in
/// https://github.com/ethereum/solidity/blob/v0.6.12/docs/abi-spec.rst#non-standard-packed-mode,
/// it is important that no more than one of the arguments to `abi.encodePacked()` here be a
/// dynamic type (see definition in
/// https://github.com/ethereum/solidity/blob/v0.6.12/docs/abi-spec.rst#formal-specification-of-the-encoding).
bytes32 node = keccak256(abi.encodePacked(index, msg.sender, amount, vestingLength, cliffLength, vestingInterval));
require(MerkleProof.verify(merkleProof, merkleRoot, node), "Invalid proof");
// Mark it accepted and perform the granting.
_setGrantAccepted(index);
uint256 tokenId = ICommunityRewards(communityRewards).grant(
msg.sender,
amount,
vestingLength,
cliffLength,
vestingInterval
);
emit GrantAccepted(tokenId, index, msg.sender, amount, vestingLength, cliffLength, vestingInterval);
}
}
// SPDX-License-Identifier: GPL-3.0-only
// solhint-disable-next-line max-line-length
// Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/interfaces/IMerkleDistributor.sol.
pragma solidity 0.6.12;
/// @notice Enables the granting of a CommunityRewards grant, if the grant details exist in this
/// contract's Merkle root.
interface IMerkleDistributor {
/// @notice Returns the address of the CommunityRewards contract whose grants are distributed by this contract.
function communityRewards() external view returns (address);
/// @notice Returns the merkle root of the merkle tree containing grant details available to accept.
function merkleRoot() external view returns (bytes32);
/// @notice Returns true if the index has been marked accepted.
function isGrantAccepted(uint256 index) external view returns (bool);
/// @notice Causes the sender to accept the grant consisting of the given details. Reverts if
/// the inputs (which includes who the sender is) are invalid.
function acceptGrant(
uint256 index,
uint256 amount,
uint256 vestingLength,
uint256 cliffLength,
uint256 vestingInterval,
bytes32[] calldata merkleProof
) external;
/// @notice This event is triggered whenever a call to #acceptGrant succeeds.
event GrantAccepted(
uint256 indexed tokenId,
uint256 indexed index,
address indexed account,
uint256 amount,
uint256 vestingLength,
uint256 cliffLength,
uint256 vestingInterval
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../core/BaseUpgradeablePausable.sol";
import "../core/ConfigHelper.sol";
import "../core/CreditLine.sol";
import "../core/GoldfinchConfig.sol";
import "../../interfaces/IERC20withDec.sol";
import "../../interfaces/ITranchedPool.sol";
import "../../interfaces/IBorrower.sol";
import "@opengsn/gsn/contracts/BaseRelayRecipient.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/**
* @title Goldfinch's Borrower contract
* @notice These contracts represent the a convenient way for a borrower to interact with Goldfinch
* They are 100% optional. However, they let us add many sophisticated and convient features for borrowers
* while still keeping our core protocol small and secure. We therefore expect most borrowers will use them.
* This contract is the "official" borrower contract that will be maintained by Goldfinch governance. However,
* in theory, anyone can fork or create their own version, or not use any contract at all. The core functionality
* is completely agnostic to whether it is interacting with a contract or an externally owned account (EOA).
* @author Goldfinch
*/
contract Borrower is BaseUpgradeablePausable, BaseRelayRecipient, IBorrower {
using SafeMath for uint256;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
address private constant USDT_ADDRESS = address(0xdAC17F958D2ee523a2206206994597C13D831ec7);
address private constant BUSD_ADDRESS = address(0x4Fabb145d64652a948d72533023f6E7A623C7C53);
address private constant GUSD_ADDRESS = address(0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd);
address private constant DAI_ADDRESS = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
function initialize(address owner, address _config) external override initializer {
require(owner != address(0) && _config != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = GoldfinchConfig(_config);
trustedForwarder = config.trustedForwarderAddress();
// Handle default approvals. Pool, and OneInch for maximum amounts
address oneInch = config.oneInchAddress();
IERC20withDec usdc = config.getUSDC();
usdc.approve(oneInch, uint256(-1));
bytes memory data = abi.encodeWithSignature("approve(address,uint256)", oneInch, uint256(-1));
invoke(USDT_ADDRESS, data);
invoke(BUSD_ADDRESS, data);
invoke(GUSD_ADDRESS, data);
invoke(DAI_ADDRESS, data);
}
function lockJuniorCapital(address poolAddress) external onlyAdmin {
ITranchedPool(poolAddress).lockJuniorCapital();
}
function lockPool(address poolAddress) external onlyAdmin {
ITranchedPool(poolAddress).lockPool();
}
/**
* @notice Allows a borrower to drawdown on their creditline through the CreditDesk.
* @param poolAddress The creditline from which they would like to drawdown
* @param amount The amount, in USDC atomic units, that a borrower wishes to drawdown
* @param addressToSendTo The address where they would like the funds sent. If the zero address is passed,
* it will be defaulted to the contracts address (msg.sender). This is a convenience feature for when they would
* like the funds sent to an exchange or alternate wallet, different from the authentication address
*/
function drawdown(
address poolAddress,
uint256 amount,
address addressToSendTo
) external onlyAdmin {
ITranchedPool(poolAddress).drawdown(amount);
if (addressToSendTo == address(0) || addressToSendTo == address(this)) {
addressToSendTo = _msgSender();
}
transferERC20(config.usdcAddress(), addressToSendTo, amount);
}
function drawdownWithSwapOnOneInch(
address poolAddress,
uint256 amount,
address addressToSendTo,
address toToken,
uint256 minTargetAmount,
uint256[] calldata exchangeDistribution
) public onlyAdmin {
// Drawdown to the Borrower contract
ITranchedPool(poolAddress).drawdown(amount);
// Do the swap
swapOnOneInch(config.usdcAddress(), toToken, amount, minTargetAmount, exchangeDistribution);
// Default to sending to the owner, and don't let funds stay in this contract
if (addressToSendTo == address(0) || addressToSendTo == address(this)) {
addressToSendTo = _msgSender();
}
// Fulfill the send to
bytes memory _data = abi.encodeWithSignature("balanceOf(address)", address(this));
uint256 receivedAmount = toUint256(invoke(toToken, _data));
transferERC20(toToken, addressToSendTo, receivedAmount);
}
function transferERC20(
address token,
address to,
uint256 amount
) public onlyAdmin {
bytes memory _data = abi.encodeWithSignature("transfer(address,uint256)", to, amount);
invoke(token, _data);
}
/**
* @notice Allows a borrower to payback loans by calling the `pay` function directly on the CreditDesk
* @param poolAddress The credit line to be paid back
* @param amount The amount, in USDC atomic units, that the borrower wishes to pay
*/
function pay(address poolAddress, uint256 amount) external onlyAdmin {
IERC20withDec usdc = config.getUSDC();
bool success = usdc.transferFrom(_msgSender(), address(this), amount);
require(success, "Failed to transfer USDC");
_transferAndPay(usdc, poolAddress, amount);
}
function payMultiple(address[] calldata pools, uint256[] calldata amounts) external onlyAdmin {
require(pools.length == amounts.length, "Pools and amounts must be the same length");
uint256 totalAmount;
for (uint256 i = 0; i < amounts.length; i++) {
totalAmount = totalAmount.add(amounts[i]);
}
IERC20withDec usdc = config.getUSDC();
// Do a single transfer, which is cheaper
bool success = usdc.transferFrom(_msgSender(), address(this), totalAmount);
require(success, "Failed to transfer USDC");
for (uint256 i = 0; i < amounts.length; i++) {
_transferAndPay(usdc, pools[i], amounts[i]);
}
}
function payInFull(address poolAddress, uint256 amount) external onlyAdmin {
IERC20withDec usdc = config.getUSDC();
bool success = usdc.transferFrom(_msgSender(), address(this), amount);
require(success, "Failed to transfer USDC");
_transferAndPay(usdc, poolAddress, amount);
require(ITranchedPool(poolAddress).creditLine().balance() == 0, "Failed to fully pay off creditline");
}
function payWithSwapOnOneInch(
address poolAddress,
uint256 originAmount,
address fromToken,
uint256 minTargetAmount,
uint256[] calldata exchangeDistribution
) external onlyAdmin {
transferFrom(fromToken, _msgSender(), address(this), originAmount);
IERC20withDec usdc = config.getUSDC();
swapOnOneInch(fromToken, address(usdc), originAmount, minTargetAmount, exchangeDistribution);
uint256 usdcBalance = usdc.balanceOf(address(this));
_transferAndPay(usdc, poolAddress, usdcBalance);
}
function payMultipleWithSwapOnOneInch(
address[] calldata pools,
uint256[] calldata minAmounts,
uint256 originAmount,
address fromToken,
uint256[] calldata exchangeDistribution
) external onlyAdmin {
require(pools.length == minAmounts.length, "Pools and amounts must be the same length");
uint256 totalMinAmount = 0;
for (uint256 i = 0; i < minAmounts.length; i++) {
totalMinAmount = totalMinAmount.add(minAmounts[i]);
}
transferFrom(fromToken, _msgSender(), address(this), originAmount);
IERC20withDec usdc = config.getUSDC();
swapOnOneInch(fromToken, address(usdc), originAmount, totalMinAmount, exchangeDistribution);
for (uint256 i = 0; i < minAmounts.length; i++) {
_transferAndPay(usdc, pools[i], minAmounts[i]);
}
uint256 remainingUSDC = usdc.balanceOf(address(this));
if (remainingUSDC > 0) {
_transferAndPay(usdc, pools[0], remainingUSDC);
}
}
function _transferAndPay(
IERC20withDec usdc,
address poolAddress,
uint256 amount
) internal {
ITranchedPool pool = ITranchedPool(poolAddress);
// We don't use transferFrom since it would require a separate approval per creditline
bool success = usdc.transfer(address(pool.creditLine()), amount);
require(success, "USDC Transfer to creditline failed");
pool.assess();
}
function transferFrom(
address erc20,
address sender,
address recipient,
uint256 amount
) internal {
bytes memory _data;
// Do a low-level invoke on this transfer, since Tether fails if we use the normal IERC20 interface
_data = abi.encodeWithSignature("transferFrom(address,address,uint256)", sender, recipient, amount);
invoke(address(erc20), _data);
}
function swapOnOneInch(
address fromToken,
address toToken,
uint256 originAmount,
uint256 minTargetAmount,
uint256[] calldata exchangeDistribution
) internal {
bytes memory _data = abi.encodeWithSignature(
"swap(address,address,uint256,uint256,uint256[],uint256)",
fromToken,
toToken,
originAmount,
minTargetAmount,
exchangeDistribution,
0
);
invoke(config.oneInchAddress(), _data);
}
/**
* @notice Performs a generic transaction.
* @param _target The address for the transaction.
* @param _data The data of the transaction.
* Mostly copied from Argent:
* https://github.com/argentlabs/argent-contracts/blob/develop/contracts/wallet/BaseWallet.sol#L111
*/
function invoke(address _target, bytes memory _data) internal returns (bytes memory) {
// External contracts can be compiled with different Solidity versions
// which can cause "revert without reason" when called through,
// for example, a standard IERC20 ABI compiled on the latest version.
// This low-level call avoids that issue.
bool success;
bytes memory _res;
// solhint-disable-next-line avoid-low-level-calls
(success, _res) = _target.call(_data);
if (!success && _res.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
} else if (!success) {
revert("VM: wallet invoke reverted");
}
return _res;
}
function toUint256(bytes memory _bytes) internal pure returns (uint256 value) {
assembly {
value := mload(add(_bytes, 0x20))
}
}
// OpenZeppelin contracts come with support for GSN _msgSender() (which just defaults to msg.sender)
// Since there are two different versions of the function in the hierarchy, we need to instruct solidity to
// use the relay recipient version which can actually pull the real sender from the parameters.
// https://www.notion.so/My-contract-is-using-OpenZeppelin-How-do-I-add-GSN-support-2bee7e9d5f774a0cbb60d3a8de03e9fb
function _msgSender() internal view override(ContextUpgradeSafe, BaseRelayRecipient) returns (address payable) {
return BaseRelayRecipient._msgSender();
}
function _msgData() internal view override(ContextUpgradeSafe, BaseRelayRecipient) returns (bytes memory ret) {
return BaseRelayRecipient._msgData();
}
function versionRecipient() external view override returns (string memory) {
return "2.0.0";
}
}
// SPDX-Licence-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IBorrower {
function initialize(address owner, address _config) external;
}
// SPDX-License-Identifier:MIT
// solhint-disable no-inline-assembly
pragma solidity ^0.6.2;
import "./interfaces/IRelayRecipient.sol";
/**
* A base contract to be inherited by any contract that want to receive relayed transactions
* A subclass must use "_msgSender()" instead of "msg.sender"
*/
abstract contract BaseRelayRecipient is IRelayRecipient {
/*
* Forwarder singleton we accept calls from
*/
address public trustedForwarder;
function isTrustedForwarder(address forwarder) public override view returns(bool) {
return forwarder == trustedForwarder;
}
/**
* return the sender of this call.
* if the call came through our trusted forwarder, return the original sender.
* otherwise, return `msg.sender`.
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal override virtual view returns (address payable ret) {
if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) {
// At this point we know that the sender is a trusted forwarder,
// so we trust that the last bytes of msg.data are the verified sender address.
// extract sender address from the end of msg.data
assembly {
ret := shr(96,calldataload(sub(calldatasize(),20)))
}
} else {
return msg.sender;
}
}
/**
* return the msg.data of this call.
* if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes
* of the msg.data - so this method will strip those 20 bytes off.
* otherwise, return `msg.data`
* should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly
* signing or hashing the
*/
function _msgData() internal override virtual view returns (bytes memory ret) {
if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) {
// At this point we know that the sender is a trusted forwarder,
// we copy the msg.data , except the last 20 bytes (and update the total length)
assembly {
let ptr := mload(0x40)
// copy only size-20 bytes
let size := sub(calldatasize(),20)
// structure RLP data as <offset> <length> <bytes>
mstore(ptr, 0x20)
mstore(add(ptr,32), size)
calldatacopy(add(ptr,64), 0, size)
return(ptr, add(size,64))
}
} else {
return msg.data;
}
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.6.2;
/**
* a contract must implement this interface in order to support relayed transaction.
* It is better to inherit the BaseRelayRecipient as its implementation.
*/
abstract contract IRelayRecipient {
/**
* return if the forwarder is trusted to forward relayed transactions to us.
* the forwarder is required to verify the sender's signature, and verify
* the call is not a replay.
*/
function isTrustedForwarder(address forwarder) public virtual view returns(bool);
/**
* return the sender of this call.
* if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes
* of the msg.data.
* otherwise, return `msg.sender`
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal virtual view returns (address payable);
/**
* return the msg.data of this call.
* if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes
* of the msg.data - so this method will strip those 20 bytes off.
* otherwise, return `msg.data`
* should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly
* signing or hashing the
*/
function _msgData() internal virtual view returns (bytes memory);
function versionRecipient() external virtual view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./GoldfinchConfig.sol";
import "./BaseUpgradeablePausable.sol";
import "../../interfaces/IBorrower.sol";
import "../../interfaces/ITranchedPool.sol";
import "./ConfigHelper.sol";
/**
* @title GoldfinchFactory
* @notice Contract that allows us to create other contracts, such as CreditLines and BorrowerContracts
* Note GoldfinchFactory is a legacy name. More properly this can be considered simply the GoldfinchFactory
* @author Goldfinch
*/
contract GoldfinchFactory is BaseUpgradeablePausable {
GoldfinchConfig public config;
/// Role to allow for pool creation
bytes32 public constant BORROWER_ROLE = keccak256("BORROWER_ROLE");
using ConfigHelper for GoldfinchConfig;
event BorrowerCreated(address indexed borrower, address indexed owner);
event PoolCreated(address indexed pool, address indexed borrower);
event GoldfinchConfigUpdated(address indexed who, address configAddress);
event CreditLineCreated(address indexed creditLine);
function initialize(address owner, GoldfinchConfig _config) public initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = _config;
_performUpgrade();
}
function performUpgrade() external onlyAdmin {
_performUpgrade();
}
function _performUpgrade() internal {
if (getRoleAdmin(BORROWER_ROLE) != OWNER_ROLE) {
_setRoleAdmin(BORROWER_ROLE, OWNER_ROLE);
}
}
/**
* @notice Allows anyone to create a CreditLine contract instance
* @dev There is no value to calling this function directly. It is only meant to be called
* by a TranchedPool during it's creation process.
*/
function createCreditLine() external returns (address) {
address creditLine = deployMinimal(config.creditLineImplementationAddress());
emit CreditLineCreated(creditLine);
return creditLine;
}
/**
* @notice Allows anyone to create a Borrower contract instance
* @param owner The address that will own the new Borrower instance
*/
function createBorrower(address owner) external returns (address) {
address _borrower = deployMinimal(config.borrowerImplementationAddress());
IBorrower borrower = IBorrower(_borrower);
borrower.initialize(owner, address(config));
emit BorrowerCreated(address(borrower), owner);
return address(borrower);
}
/**
* @notice Allows anyone to create a new TranchedPool for a single borrower
* @param _borrower The borrower for whom the CreditLine will be created
* @param _juniorFeePercent The percent of senior interest allocated to junior investors, expressed as
* integer percents. eg. 20% is simply 20
* @param _limit The maximum amount a borrower can drawdown from this CreditLine
* @param _interestApr The interest amount, on an annualized basis (APR, so non-compounding), expressed as an integer.
* We assume 18 digits of precision. For example, to submit 15.34%, you would pass up 153400000000000000,
* and 5.34% would be 53400000000000000
* @param _paymentPeriodInDays How many days in each payment period.
* ie. the frequency with which they need to make payments.
* @param _termInDays Number of days in the credit term. It is used to set the `termEndTime` upon first drawdown.
* ie. The credit line should be fully paid off {_termIndays} days after the first drawdown.
* @param _lateFeeApr The additional interest you will pay if you are late. For example, if this is 3%, and your
* normal rate is 15%, then you will pay 18% while you are late. Also expressed as an 18 decimal precision integer
*
* Requirements:
* You are the admin
*/
function createPool(
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays,
uint256 _fundableAt,
uint256[] calldata _allowedUIDTypes
) external onlyAdminOrBorrower returns (address pool) {
address tranchedPoolImplAddress = config.tranchedPoolAddress();
pool = deployMinimal(tranchedPoolImplAddress);
ITranchedPool(pool).initialize(
address(config),
_borrower,
_juniorFeePercent,
_limit,
_interestApr,
_paymentPeriodInDays,
_termInDays,
_lateFeeApr,
_principalGracePeriodInDays,
_fundableAt,
_allowedUIDTypes
);
emit PoolCreated(pool, _borrower);
config.getPoolTokens().onPoolCreated(pool);
return pool;
}
function createMigratedPool(
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays,
uint256 _fundableAt,
uint256[] calldata _allowedUIDTypes
) external onlyCreditDesk returns (address pool) {
address tranchedPoolImplAddress = config.migratedTranchedPoolAddress();
pool = deployMinimal(tranchedPoolImplAddress);
ITranchedPool(pool).initialize(
address(config),
_borrower,
_juniorFeePercent,
_limit,
_interestApr,
_paymentPeriodInDays,
_termInDays,
_lateFeeApr,
_principalGracePeriodInDays,
_fundableAt,
_allowedUIDTypes
);
emit PoolCreated(pool, _borrower);
config.getPoolTokens().onPoolCreated(pool);
return pool;
}
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
// Stolen from:
// https://github.com/OpenZeppelin/openzeppelin-sdk/blob/master/packages/lib/contracts/upgradeability/ProxyFactory.sol
function deployMinimal(address _logic) internal returns (address proxy) {
bytes20 targetBytes = bytes20(_logic);
// solhint-disable-next-line no-inline-assembly
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
proxy := create(0, clone, 0x37)
}
return proxy;
}
function isBorrower() public view returns (bool) {
return hasRole(BORROWER_ROLE, _msgSender());
}
modifier onlyAdminOrBorrower() {
require(isAdmin() || isBorrower(), "Must have admin or borrower role to perform this action");
_;
}
modifier onlyCreditDesk() {
require(msg.sender == config.creditDeskAddress(), "Only the CreditDesk can call this");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@uniswap/lib/contracts/libraries/Babylonian.sol";
import "../library/SafeERC20Transfer.sol";
import "../protocol/core/ConfigHelper.sol";
import "../protocol/core/BaseUpgradeablePausable.sol";
import "../interfaces/IPoolTokens.sol";
import "../interfaces/ITranchedPool.sol";
import "../interfaces/IBackerRewards.sol";
// Basically, Every time a interest payment comes back
// we keep a running total of dollars (totalInterestReceived) until it reaches the maxInterestDollarsEligible limit
// Every dollar of interest received from 0->maxInterestDollarsEligible
// has a allocated amount of rewards based on a sqrt function.
// When a interest payment comes in for a given Pool or the pool balance increases
// we recalculate the pool's accRewardsPerPrincipalDollar
// equation ref `_calculateNewGrossGFIRewardsForInterestAmount()`:
// (sqrtNewTotalInterest - sqrtOrigTotalInterest) / sqrtMaxInterestDollarsEligible * (totalRewards / totalGFISupply)
// When a PoolToken is minted, we set the mint price to the pool's current accRewardsPerPrincipalDollar
// Every time a PoolToken withdraws rewards, we determine the allocated rewards,
// increase that PoolToken's rewardsClaimed, and transfer the owner the gfi
contract BackerRewards is IBackerRewards, BaseUpgradeablePausable, SafeERC20Transfer {
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
using SafeMath for uint256;
struct BackerRewardsInfo {
uint256 accRewardsPerPrincipalDollar; // accumulator gfi per interest dollar
}
struct BackerRewardsTokenInfo {
uint256 rewardsClaimed; // gfi claimed
uint256 accRewardsPerPrincipalDollarAtMint; // Pool's accRewardsPerPrincipalDollar at PoolToken mint()
}
uint256 public totalRewards; // total amount of GFI rewards available, times 1e18
uint256 public maxInterestDollarsEligible; // interest $ eligible for gfi rewards, times 1e18
uint256 public totalInterestReceived; // counter of total interest repayments, times 1e6
uint256 public totalRewardPercentOfTotalGFI; // totalRewards/totalGFISupply, times 1e18
mapping(uint256 => BackerRewardsTokenInfo) public tokens; // poolTokenId -> BackerRewardsTokenInfo
mapping(address => BackerRewardsInfo) public pools; // pool.address -> BackerRewardsInfo
// solhint-disable-next-line func-name-mixedcase
function __initialize__(address owner, GoldfinchConfig _config) public initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = _config;
}
/**
* @notice Calculates the accRewardsPerPrincipalDollar for a given pool,
when a interest payment is received by the protocol
* @param _interestPaymentAmount The amount of total dollars the interest payment, expects 10^6 value
*/
function allocateRewards(uint256 _interestPaymentAmount) external override onlyPool {
// note: do not use a require statment because that will TranchedPool kill execution
if (_interestPaymentAmount > 0) {
_allocateRewards(_interestPaymentAmount);
}
}
/**
* @notice Set the total gfi rewards and the % of total GFI
* @param _totalRewards The amount of GFI rewards available, expects 10^18 value
*/
function setTotalRewards(uint256 _totalRewards) public onlyAdmin {
totalRewards = _totalRewards;
uint256 totalGFISupply = config.getGFI().totalSupply();
totalRewardPercentOfTotalGFI = _totalRewards.mul(mantissa()).div(totalGFISupply).mul(100);
emit BackerRewardsSetTotalRewards(_msgSender(), _totalRewards, totalRewardPercentOfTotalGFI);
}
/**
* @notice Set the total interest received to date.
This should only be called once on contract deploy.
* @param _totalInterestReceived The amount of interest the protocol has received to date, expects 10^6 value
*/
function setTotalInterestReceived(uint256 _totalInterestReceived) public onlyAdmin {
totalInterestReceived = _totalInterestReceived;
emit BackerRewardsSetTotalInterestReceived(_msgSender(), _totalInterestReceived);
}
/**
* @notice Set the max dollars across the entire protocol that are eligible for GFI rewards
* @param _maxInterestDollarsEligible The amount of interest dollars eligible for GFI rewards, expects 10^18 value
*/
function setMaxInterestDollarsEligible(uint256 _maxInterestDollarsEligible) public onlyAdmin {
maxInterestDollarsEligible = _maxInterestDollarsEligible;
emit BackerRewardsSetMaxInterestDollarsEligible(_msgSender(), _maxInterestDollarsEligible);
}
/**
* @notice When a pool token is minted for multiple drawdowns,
set accRewardsPerPrincipalDollarAtMint to the current accRewardsPerPrincipalDollar price
* @param tokenId Pool token id
*/
function setPoolTokenAccRewardsPerPrincipalDollarAtMint(address poolAddress, uint256 tokenId) external override {
require(_msgSender() == config.poolTokensAddress(), "Invalid sender!");
require(config.getPoolTokens().validPool(poolAddress), "Invalid pool!");
if (tokens[tokenId].accRewardsPerPrincipalDollarAtMint != 0) {
return;
}
IPoolTokens poolTokens = config.getPoolTokens();
IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);
require(poolAddress == tokenInfo.pool, "PoolAddress must equal PoolToken pool address");
tokens[tokenId].accRewardsPerPrincipalDollarAtMint = pools[tokenInfo.pool].accRewardsPerPrincipalDollar;
}
/**
* @notice Calculate the gross available gfi rewards for a PoolToken
* @param tokenId Pool token id
* @return The amount of GFI claimable
*/
function poolTokenClaimableRewards(uint256 tokenId) public view returns (uint256) {
IPoolTokens poolTokens = config.getPoolTokens();
IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);
// Note: If a TranchedPool is oversubscribed, reward allocation's scale down proportionately.
uint256 diffOfAccRewardsPerPrincipalDollar = pools[tokenInfo.pool].accRewardsPerPrincipalDollar.sub(
tokens[tokenId].accRewardsPerPrincipalDollarAtMint
);
uint256 rewardsClaimed = tokens[tokenId].rewardsClaimed.mul(mantissa());
/*
equation for token claimable rewards:
token.principalAmount
* (pool.accRewardsPerPrincipalDollar - token.accRewardsPerPrincipalDollarAtMint)
- token.rewardsClaimed
*/
return
usdcToAtomic(tokenInfo.principalAmount).mul(diffOfAccRewardsPerPrincipalDollar).sub(rewardsClaimed).div(
mantissa()
);
}
/**
* @notice PoolToken request to withdraw multiple PoolTokens allocated rewards
* @param tokenIds Array of pool token id
*/
function withdrawMultiple(uint256[] calldata tokenIds) public {
require(tokenIds.length > 0, "TokensIds length must not be 0");
for (uint256 i = 0; i < tokenIds.length; i++) {
withdraw(tokenIds[i]);
}
}
/**
* @notice PoolToken request to withdraw all allocated rewards
* @param tokenId Pool token id
*/
function withdraw(uint256 tokenId) public {
uint256 totalClaimableRewards = poolTokenClaimableRewards(tokenId);
uint256 poolTokenRewardsClaimed = tokens[tokenId].rewardsClaimed;
IPoolTokens poolTokens = config.getPoolTokens();
IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);
address poolAddr = tokenInfo.pool;
require(config.getPoolTokens().validPool(poolAddr), "Invalid pool!");
require(msg.sender == poolTokens.ownerOf(tokenId), "Must be owner of PoolToken");
BaseUpgradeablePausable pool = BaseUpgradeablePausable(poolAddr);
require(!pool.paused(), "Pool withdraw paused");
ITranchedPool tranchedPool = ITranchedPool(poolAddr);
require(!tranchedPool.creditLine().isLate(), "Pool is late on payments");
tokens[tokenId].rewardsClaimed = poolTokenRewardsClaimed.add(totalClaimableRewards);
safeERC20Transfer(config.getGFI(), poolTokens.ownerOf(tokenId), totalClaimableRewards);
emit BackerRewardsClaimed(_msgSender(), tokenId, totalClaimableRewards);
}
/* Internal functions */
function _allocateRewards(uint256 _interestPaymentAmount) internal {
uint256 _totalInterestReceived = totalInterestReceived;
if (usdcToAtomic(_totalInterestReceived) >= maxInterestDollarsEligible) {
return;
}
address _poolAddress = _msgSender();
// Gross GFI Rewards earned for incoming interest dollars
uint256 newGrossRewards = _calculateNewGrossGFIRewardsForInterestAmount(_interestPaymentAmount);
ITranchedPool pool = ITranchedPool(_poolAddress);
BackerRewardsInfo storage _poolInfo = pools[_poolAddress];
uint256 totalJuniorDeposits = pool.totalJuniorDeposits();
if (totalJuniorDeposits == 0) {
return;
}
// example: (6708203932437400000000 * 10^18) / (100000*10^18)
_poolInfo.accRewardsPerPrincipalDollar = _poolInfo.accRewardsPerPrincipalDollar.add(
newGrossRewards.mul(mantissa()).div(usdcToAtomic(totalJuniorDeposits))
);
totalInterestReceived = _totalInterestReceived.add(_interestPaymentAmount);
}
/**
* @notice Calculate the rewards earned for a given interest payment
* @param _interestPaymentAmount interest payment amount times 1e6
*/
function _calculateNewGrossGFIRewardsForInterestAmount(uint256 _interestPaymentAmount)
internal
view
returns (uint256)
{
uint256 totalGFISupply = config.getGFI().totalSupply();
// incoming interest payment, times * 1e18 divided by 1e6
uint256 interestPaymentAmount = usdcToAtomic(_interestPaymentAmount);
// all-time interest payments prior to the incoming amount, times 1e18
uint256 _previousTotalInterestReceived = usdcToAtomic(totalInterestReceived);
uint256 sqrtOrigTotalInterest = Babylonian.sqrt(_previousTotalInterestReceived);
// sum of new interest payment + previous total interest payments, times 1e18
uint256 newTotalInterest = usdcToAtomic(
atomicToUSDC(_previousTotalInterestReceived).add(atomicToUSDC(interestPaymentAmount))
);
// interest payment passed the maxInterestDollarsEligible cap, should only partially be rewarded
if (newTotalInterest > maxInterestDollarsEligible) {
newTotalInterest = maxInterestDollarsEligible;
}
/*
equation:
(sqrtNewTotalInterest-sqrtOrigTotalInterest)
* totalRewardPercentOfTotalGFI
/ sqrtMaxInterestDollarsEligible
/ 100
* totalGFISupply
/ 10^18
example scenario:
- new payment = 5000*10^18
- original interest received = 0*10^18
- total reward percent = 3 * 10^18
- max interest dollars = 1 * 10^27 ($1 billion)
- totalGfiSupply = 100_000_000 * 10^18
example math:
(70710678118 - 0)
* 3000000000000000000
/ 31622776601683
/ 100
* 100000000000000000000000000
/ 10^18
= 6708203932437400000000 (6,708.2039 GFI)
*/
uint256 sqrtDiff = Babylonian.sqrt(newTotalInterest).sub(sqrtOrigTotalInterest);
uint256 sqrtMaxInterestDollarsEligible = Babylonian.sqrt(maxInterestDollarsEligible);
require(sqrtMaxInterestDollarsEligible > 0, "maxInterestDollarsEligible must not be zero");
uint256 newGrossRewards = sqrtDiff
.mul(totalRewardPercentOfTotalGFI)
.div(sqrtMaxInterestDollarsEligible)
.div(100)
.mul(totalGFISupply)
.div(mantissa());
// Extra safety check to make sure the logic is capped at a ceiling of potential rewards
// Calculating the gfi/$ for first dollar of interest to the protocol, and multiplying by new interest amount
uint256 absoluteMaxGfiCheckPerDollar = Babylonian
.sqrt((uint256)(1).mul(mantissa()))
.mul(totalRewardPercentOfTotalGFI)
.div(sqrtMaxInterestDollarsEligible)
.div(100)
.mul(totalGFISupply)
.div(mantissa());
require(
newGrossRewards < absoluteMaxGfiCheckPerDollar.mul(newTotalInterest),
"newGrossRewards cannot be greater then the max gfi per dollar"
);
return newGrossRewards;
}
function mantissa() internal pure returns (uint256) {
return uint256(10)**uint256(18);
}
function usdcMantissa() internal pure returns (uint256) {
return uint256(10)**uint256(6);
}
function usdcToAtomic(uint256 amount) internal pure returns (uint256) {
return amount.mul(mantissa()).div(usdcMantissa());
}
function atomicToUSDC(uint256 amount) internal pure returns (uint256) {
return amount.div(mantissa().div(usdcMantissa()));
}
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(_msgSender(), address(config));
}
/* ======== MODIFIERS ======== */
modifier onlyPool() {
require(config.getPoolTokens().validPool(_msgSender()), "Invalid pool!");
_;
}
/* ======== EVENTS ======== */
event GoldfinchConfigUpdated(address indexed who, address configAddress);
event BackerRewardsClaimed(address indexed owner, uint256 indexed tokenId, uint256 amount);
event BackerRewardsSetTotalRewards(address indexed owner, uint256 totalRewards, uint256 totalRewardPercentOfTotalGFI);
event BackerRewardsSetTotalInterestReceived(address indexed owner, uint256 totalInterestReceived);
event BackerRewardsSetMaxInterestDollarsEligible(address indexed owner, uint256 maxInterestDollarsEligible);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
// credit for this implementation goes to
// https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
// this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2);
// however that code costs significantly more gas
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../rewards/BackerRewards.sol";
contract TestBackerRewards is BackerRewards {
address payable public sender;
// solhint-disable-next-line modifiers/ensure-modifiers
function _setSender(address payable _sender) public {
sender = _sender;
}
function _msgSender() internal view override returns (address payable) {
if (sender != address(0)) {
return sender;
} else {
return super._msgSender();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/drafts/IERC20Permit.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "../../external/ERC721PresetMinterPauserAutoId.sol";
import "../../interfaces/IPoolTokens.sol";
import "../../interfaces/ITranchedPool.sol";
import "../../interfaces/IPoolTokens.sol";
import "../../interfaces/ISeniorPool.sol";
import "../../interfaces/IFidu.sol";
import "../core/BaseUpgradeablePausable.sol";
import "../core/GoldfinchConfig.sol";
import "../core/ConfigHelper.sol";
import "../../library/SafeERC20Transfer.sol";
contract TransferRestrictedVault is
ERC721PresetMinterPauserAutoIdUpgradeSafe,
ReentrancyGuardUpgradeSafe,
SafeERC20Transfer
{
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
using SafeMath for uint256;
struct PoolTokenPosition {
uint256 tokenId;
uint256 lockedUntil;
}
struct FiduPosition {
uint256 amount;
uint256 lockedUntil;
}
// tokenId => poolTokenPosition
mapping(uint256 => PoolTokenPosition) public poolTokenPositions;
// tokenId => fiduPosition
mapping(uint256 => FiduPosition) public fiduPositions;
/*
We are using our own initializer function so that OZ doesn't automatically
set owner as msg.sender. Also, it lets us set our config contract
*/
// solhint-disable-next-line func-name-mixedcase
function __initialize__(address owner, GoldfinchConfig _config) external initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__Context_init_unchained();
__AccessControl_init_unchained();
__ReentrancyGuard_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained("Goldfinch V2 Accredited Investor Tokens", "GFI-V2-AI");
__Pausable_init_unchained();
__ERC721Pausable_init_unchained();
config = _config;
_setupRole(PAUSER_ROLE, owner);
_setupRole(OWNER_ROLE, owner);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
function depositJunior(ITranchedPool tranchedPool, uint256 amount) public nonReentrant {
require(config.getGo().go(msg.sender), "This address has not been go-listed");
safeERC20TransferFrom(config.getUSDC(), msg.sender, address(this), amount);
approveSpender(address(tranchedPool), amount);
uint256 poolTokenId = tranchedPool.deposit(uint256(ITranchedPool.Tranches.Junior), amount);
uint256 transferRestrictionPeriodInSeconds = SECONDS_PER_DAY.mul(config.getTransferRestrictionPeriodInDays());
_tokenIdTracker.increment();
uint256 tokenId = _tokenIdTracker.current();
poolTokenPositions[tokenId] = PoolTokenPosition({
tokenId: poolTokenId,
lockedUntil: block.timestamp.add(transferRestrictionPeriodInSeconds)
});
_mint(msg.sender, tokenId);
}
function depositJuniorWithPermit(
ITranchedPool tranchedPool,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s);
depositJunior(tranchedPool, amount);
}
function depositSenior(uint256 amount) public nonReentrant {
safeERC20TransferFrom(config.getUSDC(), msg.sender, address(this), amount);
ISeniorPool seniorPool = config.getSeniorPool();
approveSpender(address(seniorPool), amount);
uint256 depositShares = seniorPool.deposit(amount);
uint256 transferRestrictionPeriodInSeconds = SECONDS_PER_DAY.mul(config.getTransferRestrictionPeriodInDays());
_tokenIdTracker.increment();
uint256 tokenId = _tokenIdTracker.current();
fiduPositions[tokenId] = FiduPosition({
amount: depositShares,
lockedUntil: block.timestamp.add(transferRestrictionPeriodInSeconds)
});
_mint(msg.sender, tokenId);
}
function depositSeniorWithPermit(
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s);
depositSenior(amount);
}
function withdrawSenior(uint256 tokenId, uint256 usdcAmount) public nonReentrant onlyTokenOwner(tokenId) {
IFidu fidu = config.getFidu();
ISeniorPool seniorPool = config.getSeniorPool();
uint256 fiduBalanceBefore = fidu.balanceOf(address(this));
uint256 receivedAmount = seniorPool.withdraw(usdcAmount);
uint256 fiduUsed = fiduBalanceBefore.sub(fidu.balanceOf(address(this)));
FiduPosition storage fiduPosition = fiduPositions[tokenId];
uint256 fiduPositionAmount = fiduPosition.amount;
require(fiduPositionAmount >= fiduUsed, "Not enough Fidu for withdrawal");
fiduPosition.amount = fiduPositionAmount.sub(fiduUsed);
safeERC20Transfer(config.getUSDC(), msg.sender, receivedAmount);
}
function withdrawSeniorInFidu(uint256 tokenId, uint256 shares) public nonReentrant onlyTokenOwner(tokenId) {
FiduPosition storage fiduPosition = fiduPositions[tokenId];
uint256 fiduPositionAmount = fiduPosition.amount;
require(fiduPositionAmount >= shares, "Not enough Fidu for withdrawal");
fiduPosition.amount = fiduPositionAmount.sub(shares);
uint256 usdcAmount = config.getSeniorPool().withdrawInFidu(shares);
safeERC20Transfer(config.getUSDC(), msg.sender, usdcAmount);
}
function withdrawJunior(uint256 tokenId, uint256 amount)
public
nonReentrant
onlyTokenOwner(tokenId)
returns (uint256 interestWithdrawn, uint256 principalWithdrawn)
{
PoolTokenPosition storage position = poolTokenPositions[tokenId];
require(position.lockedUntil > 0, "Position is empty");
IPoolTokens poolTokens = config.getPoolTokens();
uint256 poolTokenId = position.tokenId;
IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(poolTokenId);
ITranchedPool pool = ITranchedPool(tokenInfo.pool);
(interestWithdrawn, principalWithdrawn) = pool.withdraw(poolTokenId, amount);
uint256 totalWithdrawn = interestWithdrawn.add(principalWithdrawn);
safeERC20Transfer(config.getUSDC(), msg.sender, totalWithdrawn);
return (interestWithdrawn, principalWithdrawn);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId // solhint-disable-line no-unused-vars
) internal virtual override(ERC721PresetMinterPauserAutoIdUpgradeSafe) {
// AccreditedInvestor tokens can never be transferred. The underlying positions,
// however, can be transferred after the timelock expires.
require(from == address(0) || to == address(0), "TransferRestrictedVault tokens cannot be transferred");
}
/**
* @dev This method assumes that positions are mutually exclusive i.e. that the token
* represents a position in either PoolTokens or Fidu, but not both.
*/
function transferPosition(uint256 tokenId, address to) public nonReentrant {
require(ownerOf(tokenId) == msg.sender, "Cannot transfer position of token you don't own");
FiduPosition storage fiduPosition = fiduPositions[tokenId];
if (fiduPosition.lockedUntil > 0) {
require(
block.timestamp >= fiduPosition.lockedUntil,
"Underlying position cannot be transferred until lockedUntil"
);
transferFiduPosition(fiduPosition, to);
delete fiduPositions[tokenId];
}
PoolTokenPosition storage poolTokenPosition = poolTokenPositions[tokenId];
if (poolTokenPosition.lockedUntil > 0) {
require(
block.timestamp >= poolTokenPosition.lockedUntil,
"Underlying position cannot be transferred until lockedUntil"
);
transferPoolTokenPosition(poolTokenPosition, to);
delete poolTokenPositions[tokenId];
}
_burn(tokenId);
}
function transferPoolTokenPosition(PoolTokenPosition storage position, address to) internal {
IPoolTokens poolTokens = config.getPoolTokens();
poolTokens.safeTransferFrom(address(this), to, position.tokenId);
}
function transferFiduPosition(FiduPosition storage position, address to) internal {
IFidu fidu = config.getFidu();
safeERC20Transfer(fidu, to, position.amount);
}
function approveSpender(address spender, uint256 allowance) internal {
IERC20withDec usdc = config.getUSDC();
safeERC20Approve(usdc, spender, allowance);
}
modifier onlyTokenOwner(uint256 tokenId) {
require(ownerOf(tokenId) == msg.sender, "Only the token owner is allowed to call this function");
_;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
// contract IOneSplitConsts {
// // flags = FLAG_DISABLE_UNISWAP + FLAG_DISABLE_BANCOR + ...
// uint256 internal constant FLAG_DISABLE_UNISWAP = 0x01;
// uint256 internal constant DEPRECATED_FLAG_DISABLE_KYBER = 0x02; // Deprecated
// uint256 internal constant FLAG_DISABLE_BANCOR = 0x04;
// uint256 internal constant FLAG_DISABLE_OASIS = 0x08;
// uint256 internal constant FLAG_DISABLE_COMPOUND = 0x10;
// uint256 internal constant FLAG_DISABLE_FULCRUM = 0x20;
// uint256 internal constant FLAG_DISABLE_CHAI = 0x40;
// uint256 internal constant FLAG_DISABLE_AAVE = 0x80;
// uint256 internal constant FLAG_DISABLE_SMART_TOKEN = 0x100;
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_ETH = 0x200; // Deprecated, Turned off by default
// uint256 internal constant FLAG_DISABLE_BDAI = 0x400;
// uint256 internal constant FLAG_DISABLE_IEARN = 0x800;
// uint256 internal constant FLAG_DISABLE_CURVE_COMPOUND = 0x1000;
// uint256 internal constant FLAG_DISABLE_CURVE_USDT = 0x2000;
// uint256 internal constant FLAG_DISABLE_CURVE_Y = 0x4000;
// uint256 internal constant FLAG_DISABLE_CURVE_BINANCE = 0x8000;
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_DAI = 0x10000; // Deprecated, Turned off by default
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDC = 0x20000; // Deprecated, Turned off by default
// uint256 internal constant FLAG_DISABLE_CURVE_SYNTHETIX = 0x40000;
// uint256 internal constant FLAG_DISABLE_WETH = 0x80000;
// uint256 internal constant FLAG_DISABLE_UNISWAP_COMPOUND = 0x100000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
// uint256 internal constant FLAG_DISABLE_UNISWAP_CHAI = 0x200000; // Works only when ETH<>DAI or FLAG_ENABLE_MULTI_PATH_ETH
// uint256 internal constant FLAG_DISABLE_UNISWAP_AAVE = 0x400000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
// uint256 internal constant FLAG_DISABLE_IDLE = 0x800000;
// uint256 internal constant FLAG_DISABLE_MOONISWAP = 0x1000000;
// uint256 internal constant FLAG_DISABLE_UNISWAP_V2 = 0x2000000;
// uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ETH = 0x4000000;
// uint256 internal constant FLAG_DISABLE_UNISWAP_V2_DAI = 0x8000000;
// uint256 internal constant FLAG_DISABLE_UNISWAP_V2_USDC = 0x10000000;
// uint256 internal constant FLAG_DISABLE_ALL_SPLIT_SOURCES = 0x20000000;
// uint256 internal constant FLAG_DISABLE_ALL_WRAP_SOURCES = 0x40000000;
// uint256 internal constant FLAG_DISABLE_CURVE_PAX = 0x80000000;
// uint256 internal constant FLAG_DISABLE_CURVE_RENBTC = 0x100000000;
// uint256 internal constant FLAG_DISABLE_CURVE_TBTC = 0x200000000;
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDT = 0x400000000; // Deprecated, Turned off by default
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_WBTC = 0x800000000; // Deprecated, Turned off by default
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_TBTC = 0x1000000000; // Deprecated, Turned off by default
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_RENBTC = 0x2000000000; // Deprecated, Turned off by default
// uint256 internal constant FLAG_DISABLE_DFORCE_SWAP = 0x4000000000;
// uint256 internal constant FLAG_DISABLE_SHELL = 0x8000000000;
// uint256 internal constant FLAG_ENABLE_CHI_BURN = 0x10000000000;
// uint256 internal constant FLAG_DISABLE_MSTABLE_MUSD = 0x20000000000;
// uint256 internal constant FLAG_DISABLE_CURVE_SBTC = 0x40000000000;
// uint256 internal constant FLAG_DISABLE_DMM = 0x80000000000;
// uint256 internal constant FLAG_DISABLE_UNISWAP_ALL = 0x100000000000;
// uint256 internal constant FLAG_DISABLE_CURVE_ALL = 0x200000000000;
// uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ALL = 0x400000000000;
// uint256 internal constant FLAG_DISABLE_SPLIT_RECALCULATION = 0x800000000000;
// uint256 internal constant FLAG_DISABLE_BALANCER_ALL = 0x1000000000000;
// uint256 internal constant FLAG_DISABLE_BALANCER_1 = 0x2000000000000;
// uint256 internal constant FLAG_DISABLE_BALANCER_2 = 0x4000000000000;
// uint256 internal constant FLAG_DISABLE_BALANCER_3 = 0x8000000000000;
// uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_UNISWAP_RESERVE = 0x10000000000000; // Deprecated, Turned off by default
// uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_OASIS_RESERVE = 0x20000000000000; // Deprecated, Turned off by default
// uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_BANCOR_RESERVE = 0x40000000000000; // Deprecated, Turned off by default
// uint256 internal constant FLAG_ENABLE_REFERRAL_GAS_SPONSORSHIP = 0x80000000000000; // Turned off by default
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_COMP = 0x100000000000000; // Deprecated, Turned off by default
// uint256 internal constant FLAG_DISABLE_KYBER_ALL = 0x200000000000000;
// uint256 internal constant FLAG_DISABLE_KYBER_1 = 0x400000000000000;
// uint256 internal constant FLAG_DISABLE_KYBER_2 = 0x800000000000000;
// uint256 internal constant FLAG_DISABLE_KYBER_3 = 0x1000000000000000;
// uint256 internal constant FLAG_DISABLE_KYBER_4 = 0x2000000000000000;
// uint256 internal constant FLAG_ENABLE_CHI_BURN_BY_ORIGIN = 0x4000000000000000;
// uint256 internal constant FLAG_DISABLE_MOONISWAP_ALL = 0x8000000000000000;
// uint256 internal constant FLAG_DISABLE_MOONISWAP_ETH = 0x10000000000000000;
// uint256 internal constant FLAG_DISABLE_MOONISWAP_DAI = 0x20000000000000000;
// uint256 internal constant FLAG_DISABLE_MOONISWAP_USDC = 0x40000000000000000;
// uint256 internal constant FLAG_DISABLE_MOONISWAP_POOL_TOKEN = 0x80000000000000000;
// }
interface IOneSplit {
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
) external view returns (uint256 returnAmount, uint256[] memory distribution);
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
external
view
returns (
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
);
function swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags
) external payable returns (uint256 returnAmount);
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20MinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
}
function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
pragma solidity ^0.6.0;
import "./ERC20.sol";
import "../../utils/Pausable.sol";
import "../../Initializable.sol";
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20PausableUpgradeSafe is Initializable, ERC20UpgradeSafe, PausableUpgradeSafe {
function __ERC20Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
}
function __ERC20Pausable_init_unchained() internal initializer {
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
uint256[50] private __gap;
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./ERC20.sol";
import "../../Initializable.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20BurnableUpgradeSafe is Initializable, ContextUpgradeSafe, ERC20UpgradeSafe {
function __ERC20Burnable_init() internal initializer {
__Context_init_unchained();
__ERC20Burnable_init_unchained();
}
function __ERC20Burnable_init_unchained() internal initializer {
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
uint256[50] private __gap;
}
pragma solidity ^0.6.0;
import "../access/AccessControl.sol";
import "../GSN/Context.sol";
import "../token/ERC20/ERC20.sol";
import "../token/ERC20/ERC20Burnable.sol";
import "../token/ERC20/ERC20Pausable.sol";
import "../Initializable.sol";
/**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to aother accounts
*/
contract ERC20PresetMinterPauserUpgradeSafe is Initializable, ContextUpgradeSafe, AccessControlUpgradeSafe, ERC20BurnableUpgradeSafe, ERC20PausableUpgradeSafe {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
function initialize(string memory name, string memory symbol) public {
__ERC20PresetMinterPauser_init(name, symbol);
}
function __ERC20PresetMinterPauser_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
__ERC20_init_unchained(name, symbol);
__ERC20Burnable_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
__ERC20PresetMinterPauser_init_unchained(name, symbol);
}
function __ERC20PresetMinterPauser_init_unchained(string memory name, string memory symbol) internal initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_mint(to, amount);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20UpgradeSafe, ERC20PausableUpgradeSafe) {
super._beforeTokenTransfer(from, to, amount);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/presets/ERC20PresetMinterPauser.sol";
import "./ConfigHelper.sol";
/**
* @title Fidu
* @notice Fidu (symbol: FIDU) is Goldfinch's liquidity token, representing shares
* in the Pool. When you deposit, we mint a corresponding amount of Fidu, and when you withdraw, we
* burn Fidu. The share price of the Pool implicitly represents the "exchange rate" between Fidu
* and USDC (or whatever currencies the Pool may allow withdraws in during the future)
* @author Goldfinch
*/
contract Fidu is ERC20PresetMinterPauserUpgradeSafe {
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
// $1 threshold to handle potential rounding errors, from differing decimals on Fidu and USDC;
uint256 public constant ASSET_LIABILITY_MATCH_THRESHOLD = 1e6;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
event GoldfinchConfigUpdated(address indexed who, address configAddress);
/*
We are using our own initializer function so we can set the owner by passing it in.
I would override the regular "initializer" function, but I can't because it's not marked
as "virtual" in the parent contract
*/
// solhint-disable-next-line func-name-mixedcase
function __initialize__(
address owner,
string calldata name,
string calldata symbol,
GoldfinchConfig _config
) external initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
__ERC20_init_unchained(name, symbol);
__ERC20Burnable_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
config = _config;
_setupRole(MINTER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
_setupRole(OWNER_ROLE, owner);
_setRoleAdmin(MINTER_ROLE, OWNER_ROLE);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
/**
* @dev 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 super call restricts to only the minter in its implementation, so we don't need to do it here.
super.mint(to, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have the MINTER_ROLE
*/
function burnFrom(address from, uint256 amount) public override {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: Must have minter role to burn");
require(canBurn(amount), "Cannot burn: it would create an asset/liability mismatch");
_burn(from, amount);
}
// Internal functions
// canMint assumes that the USDC that backs the new shares has already been sent to the Pool
function canMint(uint256 newAmount) internal view returns (bool) {
ISeniorPool seniorPool = config.getSeniorPool();
uint256 liabilities = totalSupply().add(newAmount).mul(seniorPool.sharePrice()).div(fiduMantissa());
uint256 liabilitiesInDollars = fiduToUSDC(liabilities);
uint256 _assets = seniorPool.assets();
if (_assets >= liabilitiesInDollars) {
return true;
} else {
return liabilitiesInDollars.sub(_assets) <= ASSET_LIABILITY_MATCH_THRESHOLD;
}
}
// canBurn assumes that the USDC that backed these shares has already been moved out the Pool
function canBurn(uint256 amountToBurn) internal view returns (bool) {
ISeniorPool seniorPool = config.getSeniorPool();
uint256 liabilities = totalSupply().sub(amountToBurn).mul(seniorPool.sharePrice()).div(fiduMantissa());
uint256 liabilitiesInDollars = fiduToUSDC(liabilities);
uint256 _assets = seniorPool.assets();
if (_assets >= liabilitiesInDollars) {
return true;
} else {
return liabilitiesInDollars.sub(_assets) <= ASSET_LIABILITY_MATCH_THRESHOLD;
}
}
function fiduToUSDC(uint256 amount) internal pure returns (uint256) {
return amount.div(fiduMantissa().div(usdcMantissa()));
}
function fiduMantissa() internal pure returns (uint256) {
return uint256(10)**uint256(18);
}
function usdcMantissa() internal pure returns (uint256) {
return uint256(10)**uint256(6);
}
function updateGoldfinchConfig() external {
require(hasRole(OWNER_ROLE, _msgSender()), "ERC20PresetMinterPauser: Must have minter role to change config");
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
import "./LeverageRatioStrategy.sol";
import "../../interfaces/ISeniorPoolStrategy.sol";
import "../../interfaces/ISeniorPool.sol";
import "../../interfaces/ITranchedPool.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
contract FixedLeverageRatioStrategy is LeverageRatioStrategy {
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
event GoldfinchConfigUpdated(address indexed who, address configAddress);
function initialize(address owner, GoldfinchConfig _config) public initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = _config;
}
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
function getLeverageRatio(ITranchedPool pool) public view override returns (uint256) {
return config.getLeverageRatio();
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
import "../../interfaces/ISeniorPoolStrategy.sol";
import "../../interfaces/ISeniorPool.sol";
import "../../interfaces/ITranchedPool.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
abstract contract LeverageRatioStrategy is BaseUpgradeablePausable, ISeniorPoolStrategy {
using SafeMath for uint256;
uint256 internal constant LEVERAGE_RATIO_DECIMALS = 1e18;
/**
* @notice Determines how much money to invest in the senior tranche based on what is committed to the junior
* tranche, what is committed to the senior tranche, and a leverage ratio to the junior tranche. Because
* it takes into account what is already committed to the senior tranche, the value returned by this
* function can be used "idempotently" to achieve the investment target amount without exceeding that target.
* @param seniorPool The senior pool to invest from
* @param pool The tranched pool to invest into (as the senior)
* @return The amount of money to invest into the tranched pool's senior tranche, from the senior pool
*/
function invest(ISeniorPool seniorPool, ITranchedPool pool) public view override returns (uint256) {
ITranchedPool.TrancheInfo memory juniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Junior));
ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior));
// If junior capital is not yet invested, or pool already locked, then don't invest anything.
if (juniorTranche.lockedUntil == 0 || seniorTranche.lockedUntil > 0) {
return 0;
}
return _invest(pool, juniorTranche, seniorTranche);
}
/**
* @notice A companion of `invest()`: determines how much would be returned by `invest()`, as the
* value to invest into the senior tranche, if the junior tranche were locked and the senior tranche
* were not locked.
* @param seniorPool The senior pool to invest from
* @param pool The tranched pool to invest into (as the senior)
* @return The amount of money to invest into the tranched pool's senior tranche, from the senior pool
*/
function estimateInvestment(ISeniorPool seniorPool, ITranchedPool pool) public view override returns (uint256) {
ITranchedPool.TrancheInfo memory juniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Junior));
ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior));
return _invest(pool, juniorTranche, seniorTranche);
}
function _invest(
ITranchedPool pool,
ITranchedPool.TrancheInfo memory juniorTranche,
ITranchedPool.TrancheInfo memory seniorTranche
) internal view returns (uint256) {
uint256 juniorCapital = juniorTranche.principalDeposited;
uint256 existingSeniorCapital = seniorTranche.principalDeposited;
uint256 seniorTarget = juniorCapital.mul(getLeverageRatio(pool)).div(LEVERAGE_RATIO_DECIMALS);
if (existingSeniorCapital >= seniorTarget) {
return 0;
}
return seniorTarget.sub(existingSeniorCapital);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
import "./LeverageRatioStrategy.sol";
import "../../interfaces/ISeniorPoolStrategy.sol";
import "../../interfaces/ISeniorPool.sol";
import "../../interfaces/ITranchedPool.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
contract DynamicLeverageRatioStrategy is LeverageRatioStrategy {
bytes32 public constant LEVERAGE_RATIO_SETTER_ROLE = keccak256("LEVERAGE_RATIO_SETTER_ROLE");
struct LeverageRatioInfo {
uint256 leverageRatio;
uint256 juniorTrancheLockedUntil;
}
// tranchedPoolAddress => leverageRatioInfo
mapping(address => LeverageRatioInfo) public ratios;
event LeverageRatioUpdated(
address indexed pool,
uint256 leverageRatio,
uint256 juniorTrancheLockedUntil,
bytes32 version
);
function initialize(address owner) public initializer {
require(owner != address(0), "Owner address cannot be empty");
__BaseUpgradeablePausable__init(owner);
_setupRole(LEVERAGE_RATIO_SETTER_ROLE, owner);
_setRoleAdmin(LEVERAGE_RATIO_SETTER_ROLE, OWNER_ROLE);
}
function getLeverageRatio(ITranchedPool pool) public view override returns (uint256) {
LeverageRatioInfo memory ratioInfo = ratios[address(pool)];
ITranchedPool.TrancheInfo memory juniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Junior));
ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior));
require(ratioInfo.juniorTrancheLockedUntil > 0, "Leverage ratio has not been set yet.");
if (seniorTranche.lockedUntil > 0) {
// The senior tranche is locked. Coherence check: we expect locking the senior tranche to have
// updated `juniorTranche.lockedUntil` (compared to its value when `setLeverageRatio()` was last
// called successfully).
require(
ratioInfo.juniorTrancheLockedUntil < juniorTranche.lockedUntil,
"Expected junior tranche `lockedUntil` to have been updated."
);
} else {
require(
ratioInfo.juniorTrancheLockedUntil == juniorTranche.lockedUntil,
"Leverage ratio is obsolete. Wait for its recalculation."
);
}
return ratioInfo.leverageRatio;
}
/**
* @notice Updates the leverage ratio for the specified tranched pool. The combination of the
* `juniorTranchedLockedUntil` param and the `version` param in the event emitted by this
* function are intended to enable an outside observer to verify the computation of the leverage
* ratio set by calls of this function.
* @param pool The tranched pool whose leverage ratio to update.
* @param leverageRatio The leverage ratio value to set for the tranched pool.
* @param juniorTrancheLockedUntil The `lockedUntil` timestamp, of the tranched pool's
* junior tranche, to which this calculation of `leverageRatio` corresponds, i.e. the
* value of the `lockedUntil` timestamp of the JuniorCapitalLocked event which the caller
* is calling this function in response to having observed. By providing this timestamp
* (plus an assumption that we can trust the caller to report this value accurately),
* the caller enables this function to enforce that a leverage ratio that is obsolete in
* the sense of having been calculated for an obsolete `lockedUntil` timestamp cannot be set.
* @param version An arbitrary identifier included in the LeverageRatioUpdated event emitted
* by this function, enabling the caller to describe how it calculated `leverageRatio`. Using
* the bytes32 type accommodates using git commit hashes (both the current SHA1 hashes, which
* require 20 bytes; and the future SHA256 hashes, which require 32 bytes) for this value.
*/
function setLeverageRatio(
ITranchedPool pool,
uint256 leverageRatio,
uint256 juniorTrancheLockedUntil,
bytes32 version
) public onlySetterRole {
ITranchedPool.TrancheInfo memory juniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Junior));
ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior));
// NOTE: We allow a `leverageRatio` of 0.
require(
leverageRatio <= 10 * LEVERAGE_RATIO_DECIMALS,
"Leverage ratio must not exceed 10 (adjusted for decimals)."
);
require(juniorTranche.lockedUntil > 0, "Cannot set leverage ratio if junior tranche is not locked.");
require(seniorTranche.lockedUntil == 0, "Cannot set leverage ratio if senior tranche is locked.");
require(juniorTrancheLockedUntil == juniorTranche.lockedUntil, "Invalid `juniorTrancheLockedUntil` timestamp.");
ratios[address(pool)] = LeverageRatioInfo({
leverageRatio: leverageRatio,
juniorTrancheLockedUntil: juniorTrancheLockedUntil
});
emit LeverageRatioUpdated(address(pool), leverageRatio, juniorTrancheLockedUntil, version);
}
modifier onlySetterRole() {
require(
hasRole(LEVERAGE_RATIO_SETTER_ROLE, _msgSender()),
"Must have leverage-ratio setter role to perform this action"
);
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.5 <0.8.0;
import "../token/ERC20/ERC20.sol";
import "./IERC20Permit.sol";
import "../cryptography/ECDSA.sol";
import "../utils/Counters.sol";
import "./EIP712.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping (address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) internal EIP712(name, "1") {
}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(
abi.encode(
_PERMIT_TYPEHASH,
owner,
spender,
value,
_nonces[owner].current(),
deadline
)
);
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_nonces[owner].increment();
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) internal {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = _getChainId();
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view virtual returns (bytes32) {
if (_getChainId() == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) {
return keccak256(
abi.encode(
typeHash,
name,
version,
_getChainId(),
address(this)
)
);
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ERC20.sol";
import "../../utils/Pausable.sol";
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20Pausable is ERC20, Pausable {
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./ERC20.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
using SafeMath for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Pausable.sol";
/**
* @title GFI
* @notice GFI is Goldfinch's governance token.
* @author Goldfinch
*/
contract GFI is Context, AccessControl, ERC20Burnable, ERC20Pausable {
using SafeMath for uint256;
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/// The maximum number of tokens that can be minted
uint256 public cap;
event CapUpdated(address indexed who, uint256 cap);
constructor(
address owner,
string memory name,
string memory symbol,
uint256 initialCap
) public ERC20(name, symbol) {
cap = initialCap;
_setupRole(MINTER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
_setupRole(OWNER_ROLE, owner);
_setRoleAdmin(MINTER_ROLE, OWNER_ROLE);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
/**
* @notice create and send tokens to a specified address
* @dev this function will fail if the caller attempts to mint over the current cap
*/
function mint(address account, uint256 amount) public onlyMinter whenNotPaused {
require(mintingAmountIsWithinCap(amount), "Cannot mint more than cap");
_mint(account, amount);
}
/**
* @notice sets the maximum number of tokens that can be minted
* @dev the cap must be greater than the current total supply
*/
function setCap(uint256 _cap) external onlyOwner {
require(_cap >= totalSupply(), "Cannot decrease the cap below existing supply");
cap = _cap;
emit CapUpdated(_msgSender(), cap);
}
function mintingAmountIsWithinCap(uint256 amount) internal returns (bool) {
return totalSupply().add(amount) <= cap;
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() external onlyPauser {
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() external onlyPauser {
_unpause();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
modifier onlyOwner() {
require(hasRole(OWNER_ROLE, _msgSender()), "Must be owner");
_;
}
modifier onlyMinter() {
require(hasRole(MINTER_ROLE, _msgSender()), "Must be minter");
_;
}
modifier onlyPauser() {
require(hasRole(PAUSER_ROLE, _msgSender()), "Must be pauser");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
// Taken from https://github.com/opengsn/forwarder/blob/master/contracts/Forwarder.sol and adapted to work locally
// Main change is removing interface inheritance and adding a some debugging niceities
contract TestForwarder {
using ECDSA for bytes32;
struct ForwardRequest {
address from;
address to;
uint256 value;
uint256 gas;
uint256 nonce;
bytes data;
}
string public constant GENERIC_PARAMS = "address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data";
string public constant EIP712_DOMAIN_TYPE =
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"; // solhint-disable-line max-line-length
mapping(bytes32 => bool) public typeHashes;
mapping(bytes32 => bool) public domains;
// Nonces of senders, used to prevent replay attacks
mapping(address => uint256) private nonces;
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
function getNonce(address from) public view returns (uint256) {
return nonces[from];
}
constructor() public {
string memory requestType = string(abi.encodePacked("ForwardRequest(", GENERIC_PARAMS, ")"));
registerRequestTypeInternal(requestType);
}
function verify(
ForwardRequest memory req,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata sig
) external view {
_verifyNonce(req);
_verifySig(req, domainSeparator, requestTypeHash, suffixData, sig);
}
function execute(
ForwardRequest memory req,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata sig
) external payable returns (bool success, bytes memory ret) {
_verifyNonce(req);
_verifySig(req, domainSeparator, requestTypeHash, suffixData, sig);
_updateNonce(req);
// solhint-disable-next-line avoid-low-level-calls
(success, ret) = req.to.call{gas: req.gas, value: req.value}(abi.encodePacked(req.data, req.from));
// Added by Goldfinch for debugging
if (!success) {
require(success, string(ret));
}
if (address(this).balance > 0) {
//can't fail: req.from signed (off-chain) the request, so it must be an EOA...
payable(req.from).transfer(address(this).balance);
}
return (success, ret);
}
function _verifyNonce(ForwardRequest memory req) internal view {
require(nonces[req.from] == req.nonce, "nonce mismatch");
}
function _updateNonce(ForwardRequest memory req) internal {
nonces[req.from]++;
}
function registerRequestType(string calldata typeName, string calldata typeSuffix) external {
for (uint256 i = 0; i < bytes(typeName).length; i++) {
bytes1 c = bytes(typeName)[i];
require(c != "(" && c != ")", "invalid typename");
}
string memory requestType = string(abi.encodePacked(typeName, "(", GENERIC_PARAMS, ",", typeSuffix));
registerRequestTypeInternal(requestType);
}
function registerDomainSeparator(string calldata name, string calldata version) external {
uint256 chainId;
/* solhint-disable-next-line no-inline-assembly */
assembly {
chainId := chainid()
}
bytes memory domainValue = abi.encode(
keccak256(bytes(EIP712_DOMAIN_TYPE)),
keccak256(bytes(name)),
keccak256(bytes(version)),
chainId,
address(this)
);
bytes32 domainHash = keccak256(domainValue);
domains[domainHash] = true;
emit DomainRegistered(domainHash, domainValue);
}
function registerRequestTypeInternal(string memory requestType) internal {
bytes32 requestTypehash = keccak256(bytes(requestType));
typeHashes[requestTypehash] = true;
emit RequestTypeRegistered(requestTypehash, requestType);
}
event DomainRegistered(bytes32 indexed domainSeparator, bytes domainValue);
event RequestTypeRegistered(bytes32 indexed typeHash, string typeStr);
function _verifySig(
ForwardRequest memory req,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes memory suffixData,
bytes memory sig
) internal view {
require(domains[domainSeparator], "unregistered domain separator");
require(typeHashes[requestTypeHash], "unregistered request typehash");
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", domainSeparator, keccak256(_getEncoded(req, requestTypeHash, suffixData)))
);
require(digest.recover(sig) == req.from, "signature mismatch");
}
function _getEncoded(
ForwardRequest memory req,
bytes32 requestTypeHash,
bytes memory suffixData
) public pure returns (bytes memory) {
return
abi.encodePacked(
requestTypeHash,
abi.encode(req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data)),
suffixData
);
}
}
// contracts/GLDToken.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/drafts/ERC20Permit.sol";
contract TestERC20 is ERC20("USD Coin", "USDC"), ERC20Permit("USD Coin") {
constructor(uint256 initialSupply, uint8 decimals) public {
_setupDecimals(decimals);
_mint(msg.sender, initialSupply);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../external/ERC721PresetMinterPauserAutoId.sol";
import "./GoldfinchConfig.sol";
import "./ConfigHelper.sol";
import "../../interfaces/ITranchedPool.sol";
import "../../interfaces/IPoolTokens.sol";
/**
* @title PoolTokens
* @notice PoolTokens is an ERC721 compliant contract, which can represent
* junior tranche or senior tranche shares of any of the borrower pools.
* @author Goldfinch
*/
contract PoolTokens is IPoolTokens, ERC721PresetMinterPauserAutoIdUpgradeSafe {
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
struct PoolInfo {
uint256 totalMinted;
uint256 totalPrincipalRedeemed;
bool created;
}
// tokenId => tokenInfo
mapping(uint256 => TokenInfo) public tokens;
// poolAddress => poolInfo
mapping(address => PoolInfo) public pools;
event TokenMinted(
address indexed owner,
address indexed pool,
uint256 indexed tokenId,
uint256 amount,
uint256 tranche
);
event TokenRedeemed(
address indexed owner,
address indexed pool,
uint256 indexed tokenId,
uint256 principalRedeemed,
uint256 interestRedeemed,
uint256 tranche
);
event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId);
event GoldfinchConfigUpdated(address indexed who, address configAddress);
/*
We are using our own initializer function so that OZ doesn't automatically
set owner as msg.sender. Also, it lets us set our config contract
*/
// solhint-disable-next-line func-name-mixedcase
function __initialize__(address owner, GoldfinchConfig _config) external initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__Context_init_unchained();
__AccessControl_init_unchained();
__ERC165_init_unchained();
// This is setting name and symbol of the NFT's
__ERC721_init_unchained("Goldfinch V2 Pool Tokens", "GFI-V2-PT");
__Pausable_init_unchained();
__ERC721Pausable_init_unchained();
config = _config;
_setupRole(PAUSER_ROLE, owner);
_setupRole(OWNER_ROLE, owner);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
/**
* @notice Called by pool to create a debt position in a particular tranche and amount
* @param params Struct containing the tranche and the amount
* @param to The address that should own the position
* @return tokenId The token ID (auto-incrementing integer across all pools)
*/
function mint(MintParams calldata params, address to)
external
virtual
override
onlyPool
whenNotPaused
returns (uint256 tokenId)
{
address poolAddress = _msgSender();
tokenId = createToken(params, poolAddress);
_mint(to, tokenId);
config.getBackerRewards().setPoolTokenAccRewardsPerPrincipalDollarAtMint(_msgSender(), tokenId);
emit TokenMinted(to, poolAddress, tokenId, params.principalAmount, params.tranche);
return tokenId;
}
/**
* @notice Updates a token to reflect the principal and interest amounts that have been redeemed.
* @param tokenId The token id to update (must be owned by the pool calling this function)
* @param principalRedeemed The incremental amount of principal redeemed (cannot be more than principal deposited)
* @param interestRedeemed The incremental amount of interest redeemed
*/
function redeem(
uint256 tokenId,
uint256 principalRedeemed,
uint256 interestRedeemed
) external virtual override onlyPool whenNotPaused {
TokenInfo storage token = tokens[tokenId];
address poolAddr = token.pool;
require(token.pool != address(0), "Invalid tokenId");
require(_msgSender() == poolAddr, "Only the token's pool can redeem");
PoolInfo storage pool = pools[poolAddr];
pool.totalPrincipalRedeemed = pool.totalPrincipalRedeemed.add(principalRedeemed);
require(pool.totalPrincipalRedeemed <= pool.totalMinted, "Cannot redeem more than we minted");
token.principalRedeemed = token.principalRedeemed.add(principalRedeemed);
require(
token.principalRedeemed <= token.principalAmount,
"Cannot redeem more than principal-deposited amount for token"
);
token.interestRedeemed = token.interestRedeemed.add(interestRedeemed);
emit TokenRedeemed(ownerOf(tokenId), poolAddr, tokenId, principalRedeemed, interestRedeemed, token.tranche);
}
/**
* @dev Burns a specific ERC721 token, and removes the data from our mappings
* @param tokenId uint256 id of the ERC721 token to be burned.
*/
function burn(uint256 tokenId) external virtual override whenNotPaused {
TokenInfo memory token = _getTokenInfo(tokenId);
bool canBurn = _isApprovedOrOwner(_msgSender(), tokenId);
bool fromTokenPool = _validPool(_msgSender()) && token.pool == _msgSender();
address owner = ownerOf(tokenId);
require(canBurn || fromTokenPool, "ERC721Burnable: caller cannot burn this token");
require(token.principalRedeemed == token.principalAmount, "Can only burn fully redeemed tokens");
destroyAndBurn(tokenId);
emit TokenBurned(owner, token.pool, tokenId);
}
function getTokenInfo(uint256 tokenId) external view virtual override returns (TokenInfo memory) {
return _getTokenInfo(tokenId);
}
/**
* @notice Called by the GoldfinchFactory to register the pool as a valid pool. Only valid pools can mint/redeem
* tokens
* @param newPool The address of the newly created pool
*/
function onPoolCreated(address newPool) external override onlyGoldfinchFactory {
pools[newPool].created = true;
}
/**
* @notice Returns a boolean representing whether the spender is the owner or the approved spender of the token
* @param spender The address to check
* @param tokenId The token id to check for
* @return True if approved to redeem/transfer/burn the token, false if not
*/
function isApprovedOrOwner(address spender, uint256 tokenId) external view override returns (bool) {
return _isApprovedOrOwner(spender, tokenId);
}
function validPool(address sender) public view virtual override returns (bool) {
return _validPool(sender);
}
function createToken(MintParams calldata params, address poolAddress) internal returns (uint256 tokenId) {
PoolInfo storage pool = pools[poolAddress];
_tokenIdTracker.increment();
tokenId = _tokenIdTracker.current();
tokens[tokenId] = TokenInfo({
pool: poolAddress,
tranche: params.tranche,
principalAmount: params.principalAmount,
principalRedeemed: 0,
interestRedeemed: 0
});
pool.totalMinted = pool.totalMinted.add(params.principalAmount);
return tokenId;
}
function destroyAndBurn(uint256 tokenId) internal {
delete tokens[tokenId];
_burn(tokenId);
}
function _validPool(address poolAddress) internal view virtual returns (bool) {
return pools[poolAddress].created;
}
function _getTokenInfo(uint256 tokenId) internal view returns (TokenInfo memory) {
return tokens[tokenId];
}
/**
* @notice Migrates to a new goldfinch config address
*/
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
modifier onlyAdmin() {
require(isAdmin(), "Must have admin role to perform this action");
_;
}
function isAdmin() public view returns (bool) {
return hasRole(OWNER_ROLE, _msgSender());
}
modifier onlyGoldfinchFactory() {
require(_msgSender() == config.goldfinchFactoryAddress(), "Only Goldfinch factory is allowed");
_;
}
modifier onlyPool() {
require(_validPool(_msgSender()), "Invalid pool!");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/PoolTokens.sol";
contract TestPoolTokens is PoolTokens {
bool public disablePoolValidation;
address payable public sender;
// solhint-disable-next-line modifiers/ensure-modifiers
function _disablePoolValidation(bool shouldDisable) public {
disablePoolValidation = shouldDisable;
}
// solhint-disable-next-line modifiers/ensure-modifiers
function _setSender(address payable _sender) public {
sender = _sender;
}
function _validPool(address _sender) internal view override returns (bool) {
if (disablePoolValidation) {
return true;
} else {
return super._validPool(_sender);
}
}
function _msgSender() internal view override returns (address payable) {
if (sender != address(0)) {
return sender;
} else {
return super._msgSender();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IV2CreditLine.sol";
import "./IV1CreditLine.sol";
import "./ITranchedPool.sol";
abstract contract IMigratedTranchedPool is ITranchedPool {
function migrateCreditLineToV2(
IV1CreditLine clToMigrate,
uint256 termEndTime,
uint256 nextDueTime,
uint256 interestAccruedAsOf,
uint256 lastFullPaymentTime,
uint256 totalInterestPaid
) external virtual returns (IV2CreditLine);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
abstract contract IV1CreditLine {
address public borrower;
address public underwriter;
uint256 public limit;
uint256 public interestApr;
uint256 public paymentPeriodInDays;
uint256 public termInDays;
uint256 public lateFeeApr;
uint256 public balance;
uint256 public interestOwed;
uint256 public principalOwed;
uint256 public termEndBlock;
uint256 public nextDueBlock;
uint256 public interestAccruedAsOfBlock;
uint256 public writedownAmount;
uint256 public lastFullPaymentBlock;
function setLimit(uint256 newAmount) external virtual;
function setBalance(uint256 newBalance) external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./TranchedPool.sol";
import "../../interfaces/IV1CreditLine.sol";
import "../../interfaces/IMigratedTranchedPool.sol";
contract MigratedTranchedPool is TranchedPool, IMigratedTranchedPool {
bool public migrated;
function migrateCreditLineToV2(
IV1CreditLine clToMigrate,
uint256 termEndTime,
uint256 nextDueTime,
uint256 interestAccruedAsOf,
uint256 lastFullPaymentTime,
uint256 totalInterestPaid
) external override returns (IV2CreditLine) {
require(msg.sender == config.creditDeskAddress(), "Only credit desk can call this");
require(!migrated, "Already migrated");
// Set accounting state vars.
IV2CreditLine newCl = creditLine;
newCl.setBalance(clToMigrate.balance());
newCl.setInterestOwed(clToMigrate.interestOwed());
newCl.setPrincipalOwed(clToMigrate.principalOwed());
newCl.setTermEndTime(termEndTime);
newCl.setNextDueTime(nextDueTime);
newCl.setInterestAccruedAsOf(interestAccruedAsOf);
newCl.setLastFullPaymentTime(lastFullPaymentTime);
newCl.setTotalInterestAccrued(totalInterestPaid.add(clToMigrate.interestOwed()));
migrateDeposits(clToMigrate, totalInterestPaid);
migrated = true;
return newCl;
}
function migrateDeposits(IV1CreditLine clToMigrate, uint256 totalInterestPaid) internal {
// Mint junior tokens to the SeniorPool, equal to current cl balance;
require(!locked(), "Pool has been locked");
// Hardcode to always get the JuniorTranche, since the migration case is when
// the senior pool took the entire investment. Which we're expressing as the junior tranche
uint256 tranche = uint256(ITranchedPool.Tranches.Junior);
TrancheInfo storage trancheInfo = getTrancheInfo(tranche);
require(trancheInfo.lockedUntil == 0, "Tranche has been locked");
trancheInfo.principalDeposited = clToMigrate.limit();
IPoolTokens.MintParams memory params = IPoolTokens.MintParams({
tranche: tranche,
principalAmount: trancheInfo.principalDeposited
});
IPoolTokens poolTokens = config.getPoolTokens();
uint256 tokenId = poolTokens.mint(params, config.seniorPoolAddress());
uint256 balancePaid = creditLine.limit().sub(creditLine.balance());
// Account for the implicit redemptions already made by the Legacy Pool
_lockJuniorCapital(poolSlices.length - 1);
_lockPool();
PoolSlice storage currentSlice = poolSlices[poolSlices.length - 1];
currentSlice.juniorTranche.lockedUntil = block.timestamp - 1;
poolTokens.redeem(tokenId, balancePaid, totalInterestPaid);
// Simulate the drawdown
currentSlice.juniorTranche.principalSharePrice = 0;
currentSlice.seniorTranche.principalSharePrice = 0;
// Set junior's sharePrice correctly
currentSlice.juniorTranche.applyByAmount(totalInterestPaid, balancePaid, totalInterestPaid, balancePaid);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
import "./Accountant.sol";
import "./CreditLine.sol";
import "./GoldfinchFactory.sol";
import "../../interfaces/IV1CreditLine.sol";
import "../../interfaces/IMigratedTranchedPool.sol";
/**
* @title Goldfinch's CreditDesk contract
* @notice Main entry point for borrowers and underwriters.
* Handles key logic for creating CreditLine's, borrowing money, repayment, etc.
* @author Goldfinch
*/
contract CreditDesk is BaseUpgradeablePausable, ICreditDesk {
uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
struct Underwriter {
uint256 governanceLimit;
address[] creditLines;
}
struct Borrower {
address[] creditLines;
}
event PaymentApplied(
address indexed payer,
address indexed creditLine,
uint256 interestAmount,
uint256 principalAmount,
uint256 remainingAmount
);
event PaymentCollected(address indexed payer, address indexed creditLine, uint256 paymentAmount);
event DrawdownMade(address indexed borrower, address indexed creditLine, uint256 drawdownAmount);
event CreditLineCreated(address indexed borrower, address indexed creditLine);
event GovernanceUpdatedUnderwriterLimit(address indexed underwriter, uint256 newLimit);
mapping(address => Underwriter) public underwriters;
mapping(address => Borrower) private borrowers;
mapping(address => address) private creditLines;
/**
* @notice Run only once, on initialization
* @param owner The address of who should have the "OWNER_ROLE" of this contract
* @param _config The address of the GoldfinchConfig contract
*/
function initialize(address owner, GoldfinchConfig _config) public initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = _config;
}
/**
* @notice Sets a particular underwriter's limit of how much credit the DAO will allow them to "create"
* @param underwriterAddress The address of the underwriter for whom the limit shall change
* @param limit What the new limit will be set to
* Requirements:
*
* - the caller must have the `OWNER_ROLE`.
*/
function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit)
external
override
onlyAdmin
whenNotPaused
{
require(withinMaxUnderwriterLimit(limit), "This limit is greater than the max allowed by the protocol");
underwriters[underwriterAddress].governanceLimit = limit;
emit GovernanceUpdatedUnderwriterLimit(underwriterAddress, limit);
}
/**
* @notice Allows a borrower to drawdown on their creditline.
* `amount` USDC is sent to the borrower, and the credit line accounting is updated.
* @param creditLineAddress The creditline from which they would like to drawdown
* @param amount The amount, in USDC atomic units, that a borrower wishes to drawdown
*
* Requirements:
*
* - the caller must be the borrower on the creditLine
*/
function drawdown(address creditLineAddress, uint256 amount)
external
override
whenNotPaused
onlyValidCreditLine(creditLineAddress)
{
CreditLine cl = CreditLine(creditLineAddress);
Borrower storage borrower = borrowers[msg.sender];
require(borrower.creditLines.length > 0, "No credit lines exist for this borrower");
require(amount > 0, "Must drawdown more than zero");
require(cl.borrower() == msg.sender, "You are not the borrower of this credit line");
require(withinTransactionLimit(amount), "Amount is over the per-transaction limit");
uint256 unappliedBalance = getUSDCBalance(creditLineAddress);
require(
withinCreditLimit(amount, unappliedBalance, cl),
"The borrower does not have enough credit limit for this drawdown"
);
uint256 balance = cl.balance();
if (balance == 0) {
cl.setInterestAccruedAsOf(currentTime());
cl.setLastFullPaymentTime(currentTime());
}
IPool pool = config.getPool();
// If there is any balance on the creditline that has not been applied yet, then use that first before
// drawing down from the pool. This is to support cases where the borrower partially pays back the
// principal before the due date, but then decides to drawdown again
uint256 amountToTransferFromCL;
if (unappliedBalance > 0) {
if (amount > unappliedBalance) {
amountToTransferFromCL = unappliedBalance;
amount = amount.sub(unappliedBalance);
} else {
amountToTransferFromCL = amount;
amount = 0;
}
bool success = pool.transferFrom(creditLineAddress, msg.sender, amountToTransferFromCL);
require(success, "Failed to drawdown");
}
(uint256 interestOwed, uint256 principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(cl, currentTime());
balance = balance.add(amount);
updateCreditLineAccounting(cl, balance, interestOwed, principalOwed);
// Must put this after we update the credit line accounting, so we're using the latest
// interestOwed
require(!isLate(cl, currentTime()), "Cannot drawdown when payments are past due");
emit DrawdownMade(msg.sender, address(cl), amount.add(amountToTransferFromCL));
if (amount > 0) {
bool success = pool.drawdown(msg.sender, amount);
require(success, "Failed to drawdown");
}
}
/**
* @notice Allows a borrower to repay their loan. Payment is *collected* immediately (by sending it to
* the individual CreditLine), but it is not *applied* unless it is after the nextDueTime, or until we assess
* the credit line (ie. payment period end).
* Any amounts over the minimum payment will be applied to outstanding principal (reducing the effective
* interest rate). If there is still any left over, it will remain in the USDC Balance
* of the CreditLine, which is held distinct from the Pool amounts, and can not be withdrawn by LP's.
* @param creditLineAddress The credit line to be paid back
* @param amount The amount, in USDC atomic units, that a borrower wishes to pay
*/
function pay(address creditLineAddress, uint256 amount)
external
override
whenNotPaused
onlyValidCreditLine(creditLineAddress)
{
require(amount > 0, "Must pay more than zero");
CreditLine cl = CreditLine(creditLineAddress);
collectPayment(cl, amount);
assessCreditLine(creditLineAddress);
}
/**
* @notice Assesses a particular creditLine. This will apply payments, which will update accounting and
* distribute gains or losses back to the pool accordingly. This function is idempotent, and anyone
* is allowed to call it.
* @param creditLineAddress The creditline that should be assessed.
*/
function assessCreditLine(address creditLineAddress)
public
override
whenNotPaused
onlyValidCreditLine(creditLineAddress)
{
CreditLine cl = CreditLine(creditLineAddress);
// Do not assess until a full period has elapsed or past due
require(cl.balance() > 0, "Must have balance to assess credit line");
// Don't assess credit lines early!
if (currentTime() < cl.nextDueTime() && !isLate(cl, currentTime())) {
return;
}
uint256 timeToAssess = calculateNextDueTime(cl);
cl.setNextDueTime(timeToAssess);
// We always want to assess for the most recently *past* nextDueTime.
// So if the recalculation above sets the nextDueTime into the future,
// then ensure we pass in the one just before this.
if (timeToAssess > currentTime()) {
uint256 secondsPerPeriod = cl.paymentPeriodInDays().mul(SECONDS_PER_DAY);
timeToAssess = timeToAssess.sub(secondsPerPeriod);
}
_applyPayment(cl, getUSDCBalance(address(cl)), timeToAssess);
}
function applyPayment(address creditLineAddress, uint256 amount)
external
override
whenNotPaused
onlyValidCreditLine(creditLineAddress)
{
CreditLine cl = CreditLine(creditLineAddress);
require(cl.borrower() == msg.sender, "You do not belong to this credit line");
_applyPayment(cl, amount, currentTime());
}
function migrateV1CreditLine(
address _clToMigrate,
address borrower,
uint256 termEndTime,
uint256 nextDueTime,
uint256 interestAccruedAsOf,
uint256 lastFullPaymentTime,
uint256 totalInterestPaid
) public onlyAdmin returns (address, address) {
IV1CreditLine clToMigrate = IV1CreditLine(_clToMigrate);
uint256 originalBalance = clToMigrate.balance();
require(clToMigrate.limit() > 0, "Can't migrate empty credit line");
require(originalBalance > 0, "Can't migrate credit line that's currently paid off");
// Ensure it is a v1 creditline by calling a function that only exists on v1
require(clToMigrate.nextDueBlock() > 0, "Invalid creditline");
if (borrower == address(0)) {
borrower = clToMigrate.borrower();
}
// We're migrating from 1e8 decimal precision of interest rates to 1e18
// So multiply the legacy rates by 1e10 to normalize them.
uint256 interestMigrationFactor = 1e10;
uint256[] memory allowedUIDTypes;
address pool = getGoldfinchFactory().createMigratedPool(
borrower,
20, // junior fee percent
clToMigrate.limit(),
clToMigrate.interestApr().mul(interestMigrationFactor),
clToMigrate.paymentPeriodInDays(),
clToMigrate.termInDays(),
clToMigrate.lateFeeApr(),
0,
0,
allowedUIDTypes
);
IV2CreditLine newCl = IMigratedTranchedPool(pool).migrateCreditLineToV2(
clToMigrate,
termEndTime,
nextDueTime,
interestAccruedAsOf,
lastFullPaymentTime,
totalInterestPaid
);
// Close out the original credit line
clToMigrate.setLimit(0);
clToMigrate.setBalance(0);
// Some sanity checks on the migration
require(newCl.balance() == originalBalance, "Balance did not migrate properly");
require(newCl.interestAccruedAsOf() == interestAccruedAsOf, "Interest accrued as of did not migrate properly");
return (address(newCl), pool);
}
/**
* @notice Simple getter for the creditlines of a given underwriter
* @param underwriterAddress The underwriter address you would like to see the credit lines of.
*/
function getUnderwriterCreditLines(address underwriterAddress) public view returns (address[] memory) {
return underwriters[underwriterAddress].creditLines;
}
/**
* @notice Simple getter for the creditlines of a given borrower
* @param borrowerAddress The borrower address you would like to see the credit lines of.
*/
function getBorrowerCreditLines(address borrowerAddress) public view returns (address[] memory) {
return borrowers[borrowerAddress].creditLines;
}
/**
* @notice This function is only meant to be used by frontends. It returns the total
* payment due for a given creditLine as of the provided timestamp. Returns 0 if no
* payment is due (e.g. asOf is before the nextDueTime)
* @param creditLineAddress The creditLine to calculate the payment for
* @param asOf The timestamp to use for the payment calculation, if it is set to 0, uses the current time
*/
function getNextPaymentAmount(address creditLineAddress, uint256 asOf)
external
view
override
onlyValidCreditLine(creditLineAddress)
returns (uint256)
{
if (asOf == 0) {
asOf = currentTime();
}
CreditLine cl = CreditLine(creditLineAddress);
if (asOf < cl.nextDueTime() && !isLate(cl, currentTime())) {
return 0;
}
(uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued(
cl,
asOf,
config.getLatenessGracePeriodInDays()
);
return cl.interestOwed().add(interestAccrued).add(cl.principalOwed().add(principalAccrued));
}
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
}
/*
* Internal Functions
*/
/**
* @notice Collects `amount` of payment for a given credit line. This sends money from the payer to the credit line.
* Note that payment is not *applied* when calling this function. Only collected (ie. held) for later application.
* @param cl The CreditLine the payment will be collected for.
* @param amount The amount, in USDC atomic units, to be collected
*/
function collectPayment(CreditLine cl, uint256 amount) internal {
require(withinTransactionLimit(amount), "Amount is over the per-transaction limit");
emit PaymentCollected(msg.sender, address(cl), amount);
bool success = config.getPool().transferFrom(msg.sender, address(cl), amount);
require(success, "Failed to collect payment");
}
/**
* @notice Applies `amount` of payment for a given credit line. This moves already collected money into the Pool.
* It also updates all the accounting variables. Note that interest is always paid back first, then principal.
* Any extra after paying the minimum will go towards existing principal (reducing the
* effective interest rate). Any extra after the full loan has been paid off will remain in the
* USDC Balance of the creditLine, where it will be automatically used for the next drawdown.
* @param cl The CreditLine the payment will be collected for.
* @param amount The amount, in USDC atomic units, to be applied
* @param timestamp The timestamp on which accrual calculations should be based. This allows us
* to be precise when we assess a Credit Line
*/
function _applyPayment(
CreditLine cl,
uint256 amount,
uint256 timestamp
) internal {
(uint256 paymentRemaining, uint256 interestPayment, uint256 principalPayment) = handlePayment(
cl,
amount,
timestamp
);
IPool pool = config.getPool();
if (interestPayment > 0 || principalPayment > 0) {
emit PaymentApplied(cl.borrower(), address(cl), interestPayment, principalPayment, paymentRemaining);
pool.collectInterestAndPrincipal(address(cl), interestPayment, principalPayment);
}
}
function handlePayment(
CreditLine cl,
uint256 paymentAmount,
uint256 timestamp
)
internal
returns (
uint256,
uint256,
uint256
)
{
(uint256 interestOwed, uint256 principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(cl, timestamp);
Accountant.PaymentAllocation memory pa = Accountant.allocatePayment(
paymentAmount,
cl.balance(),
interestOwed,
principalOwed
);
uint256 newBalance = cl.balance().sub(pa.principalPayment);
// Apply any additional payment towards the balance
newBalance = newBalance.sub(pa.additionalBalancePayment);
uint256 totalPrincipalPayment = cl.balance().sub(newBalance);
uint256 paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment);
updateCreditLineAccounting(
cl,
newBalance,
interestOwed.sub(pa.interestPayment),
principalOwed.sub(pa.principalPayment)
);
assert(paymentRemaining.add(pa.interestPayment).add(totalPrincipalPayment) == paymentAmount);
return (paymentRemaining, pa.interestPayment, totalPrincipalPayment);
}
function isLate(CreditLine cl, uint256 timestamp) internal view returns (bool) {
uint256 secondsElapsedSinceFullPayment = timestamp.sub(cl.lastFullPaymentTime());
return secondsElapsedSinceFullPayment > cl.paymentPeriodInDays().mul(SECONDS_PER_DAY);
}
function getGoldfinchFactory() internal view returns (GoldfinchFactory) {
return GoldfinchFactory(config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchFactory)));
}
function updateAndGetInterestAndPrincipalOwedAsOf(CreditLine cl, uint256 timestamp)
internal
returns (uint256, uint256)
{
(uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued(
cl,
timestamp,
config.getLatenessGracePeriodInDays()
);
if (interestAccrued > 0) {
// If we've accrued any interest, update interestAccruedAsOf to the time that we've
// calculated interest for. If we've not accrued any interest, then we keep the old value so the next
// time the entire period is taken into account.
cl.setInterestAccruedAsOf(timestamp);
}
return (cl.interestOwed().add(interestAccrued), cl.principalOwed().add(principalAccrued));
}
function withinCreditLimit(
uint256 amount,
uint256 unappliedBalance,
CreditLine cl
) internal view returns (bool) {
return cl.balance().add(amount).sub(unappliedBalance) <= cl.limit();
}
function withinTransactionLimit(uint256 amount) internal view returns (bool) {
return amount <= config.getNumber(uint256(ConfigOptions.Numbers.TransactionLimit));
}
function calculateNewTermEndTime(CreditLine cl, uint256 balance) internal view returns (uint256) {
// If there's no balance, there's no loan, so there's no term end time
if (balance == 0) {
return 0;
}
// Don't allow any weird bugs where we add to your current end time. This
// function should only be used on new credit lines, when we are setting them up
if (cl.termEndTime() != 0) {
return cl.termEndTime();
}
return currentTime().add(SECONDS_PER_DAY.mul(cl.termInDays()));
}
function calculateNextDueTime(CreditLine cl) internal view returns (uint256) {
uint256 secondsPerPeriod = cl.paymentPeriodInDays().mul(SECONDS_PER_DAY);
uint256 balance = cl.balance();
uint256 nextDueTime = cl.nextDueTime();
uint256 curTimestamp = currentTime();
// You must have just done your first drawdown
if (nextDueTime == 0 && balance > 0) {
return curTimestamp.add(secondsPerPeriod);
}
// Active loan that has entered a new period, so return the *next* nextDueTime.
// But never return something after the termEndTime
if (balance > 0 && curTimestamp >= nextDueTime) {
uint256 secondsToAdvance = (curTimestamp.sub(nextDueTime).div(secondsPerPeriod)).add(1).mul(secondsPerPeriod);
nextDueTime = nextDueTime.add(secondsToAdvance);
return Math.min(nextDueTime, cl.termEndTime());
}
// Your paid off, or have not taken out a loan yet, so no next due time.
if (balance == 0 && nextDueTime != 0) {
return 0;
}
// Active loan in current period, where we've already set the nextDueTime correctly, so should not change.
if (balance > 0 && curTimestamp < nextDueTime) {
return nextDueTime;
}
revert("Error: could not calculate next due time.");
}
function currentTime() internal view virtual returns (uint256) {
return block.timestamp;
}
function underwriterCanCreateThisCreditLine(uint256 newAmount, Underwriter storage underwriter)
internal
view
returns (bool)
{
uint256 underwriterLimit = underwriter.governanceLimit;
require(underwriterLimit != 0, "underwriter does not have governance limit");
uint256 creditCurrentlyExtended = getCreditCurrentlyExtended(underwriter);
uint256 totalToBeExtended = creditCurrentlyExtended.add(newAmount);
return totalToBeExtended <= underwriterLimit;
}
function withinMaxUnderwriterLimit(uint256 amount) internal view returns (bool) {
return amount <= config.getNumber(uint256(ConfigOptions.Numbers.MaxUnderwriterLimit));
}
function getCreditCurrentlyExtended(Underwriter storage underwriter) internal view returns (uint256) {
uint256 creditExtended;
uint256 length = underwriter.creditLines.length;
for (uint256 i = 0; i < length; i++) {
CreditLine cl = CreditLine(underwriter.creditLines[i]);
creditExtended = creditExtended.add(cl.limit());
}
return creditExtended;
}
function updateCreditLineAccounting(
CreditLine cl,
uint256 balance,
uint256 interestOwed,
uint256 principalOwed
) internal nonReentrant {
// subtract cl from total loans outstanding
totalLoansOutstanding = totalLoansOutstanding.sub(cl.balance());
cl.setBalance(balance);
cl.setInterestOwed(interestOwed);
cl.setPrincipalOwed(principalOwed);
// This resets lastFullPaymentTime. These conditions assure that they have
// indeed paid off all their interest and they have a real nextDueTime. (ie. creditline isn't pre-drawdown)
uint256 nextDueTime = cl.nextDueTime();
if (interestOwed == 0 && nextDueTime != 0) {
// If interest was fully paid off, then set the last full payment as the previous due time
uint256 mostRecentLastDueTime;
if (currentTime() < nextDueTime) {
uint256 secondsPerPeriod = cl.paymentPeriodInDays().mul(SECONDS_PER_DAY);
mostRecentLastDueTime = nextDueTime.sub(secondsPerPeriod);
} else {
mostRecentLastDueTime = nextDueTime;
}
cl.setLastFullPaymentTime(mostRecentLastDueTime);
}
// Add new amount back to total loans outstanding
totalLoansOutstanding = totalLoansOutstanding.add(balance);
cl.setTermEndTime(calculateNewTermEndTime(cl, balance)); // pass in balance as a gas optimization
cl.setNextDueTime(calculateNextDueTime(cl));
}
function getUSDCBalance(address _address) internal view returns (uint256) {
return config.getUSDC().balanceOf(_address);
}
modifier onlyValidCreditLine(address clAddress) {
require(creditLines[clAddress] != address(0), "Unknown credit line");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/CreditDesk.sol";
contract TestCreditDesk is CreditDesk {
// solhint-disable-next-line modifiers/ensure-modifiers
function _setTotalLoansOutstanding(uint256 amount) public {
totalLoansOutstanding = amount;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../core/BaseUpgradeablePausable.sol";
import "../core/ConfigHelper.sol";
import "../core/CreditLine.sol";
import "../core/GoldfinchConfig.sol";
import "../../interfaces/IMigrate.sol";
/**
* @title V2 Migrator Contract
* @notice This is a one-time use contract solely for the purpose of migrating from our V1
* to our V2 architecture. It will be temporarily granted authority from the Goldfinch governance,
* and then revokes it's own authority and transfers it back to governance.
* @author Goldfinch
*/
contract V2Migrator is BaseUpgradeablePausable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant GO_LISTER_ROLE = keccak256("GO_LISTER_ROLE");
using SafeMath for uint256;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
mapping(address => address) public borrowerContracts;
event CreditLineMigrated(address indexed owner, address indexed clToMigrate, address newCl, address tranchedPool);
function initialize(address owner, address _config) external initializer {
require(owner != address(0) && _config != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = GoldfinchConfig(_config);
}
function migratePhase1(GoldfinchConfig newConfig) external onlyAdmin {
pauseEverything();
migrateToNewConfig(newConfig);
migrateToSeniorPool(newConfig);
}
function migrateCreditLines(
GoldfinchConfig newConfig,
address[][] calldata creditLinesToMigrate,
uint256[][] calldata migrationData
) external onlyAdmin {
IMigrate creditDesk = IMigrate(newConfig.creditDeskAddress());
IGoldfinchFactory factory = newConfig.getGoldfinchFactory();
for (uint256 i = 0; i < creditLinesToMigrate.length; i++) {
address[] calldata clData = creditLinesToMigrate[i];
uint256[] calldata data = migrationData[i];
address clAddress = clData[0];
address owner = clData[1];
address borrowerContract = borrowerContracts[owner];
if (borrowerContract == address(0)) {
borrowerContract = factory.createBorrower(owner);
borrowerContracts[owner] = borrowerContract;
}
(address newCl, address pool) = creditDesk.migrateV1CreditLine(
clAddress,
borrowerContract,
data[0],
data[1],
data[2],
data[3],
data[4]
);
emit CreditLineMigrated(owner, clAddress, newCl, pool);
}
}
function bulkAddToGoList(GoldfinchConfig newConfig, address[] calldata members) external onlyAdmin {
newConfig.bulkAddToGoList(members);
}
function pauseEverything() internal {
IMigrate(config.creditDeskAddress()).pause();
IMigrate(config.poolAddress()).pause();
IMigrate(config.fiduAddress()).pause();
}
function migrateToNewConfig(GoldfinchConfig newConfig) internal {
uint256 key = uint256(ConfigOptions.Addresses.GoldfinchConfig);
config.setAddress(key, address(newConfig));
IMigrate(config.creditDeskAddress()).updateGoldfinchConfig();
IMigrate(config.poolAddress()).updateGoldfinchConfig();
IMigrate(config.fiduAddress()).updateGoldfinchConfig();
IMigrate(config.goldfinchFactoryAddress()).updateGoldfinchConfig();
key = uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds);
newConfig.setNumber(key, 24 * 60 * 60);
key = uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays);
newConfig.setNumber(key, 365);
key = uint256(ConfigOptions.Numbers.LeverageRatio);
// 1e18 is the LEVERAGE_RATIO_DECIMALS
newConfig.setNumber(key, 3 * 1e18);
}
function upgradeImplementations(GoldfinchConfig _config, address[] calldata newDeployments) public {
address newPoolAddress = newDeployments[0];
address newCreditDeskAddress = newDeployments[1];
address newFiduAddress = newDeployments[2];
address newGoldfinchFactoryAddress = newDeployments[3];
bytes memory data;
IMigrate pool = IMigrate(_config.poolAddress());
IMigrate creditDesk = IMigrate(_config.creditDeskAddress());
IMigrate fidu = IMigrate(_config.fiduAddress());
IMigrate goldfinchFactory = IMigrate(_config.goldfinchFactoryAddress());
// Upgrade implementations
pool.changeImplementation(newPoolAddress, data);
creditDesk.changeImplementation(newCreditDeskAddress, data);
fidu.changeImplementation(newFiduAddress, data);
goldfinchFactory.changeImplementation(newGoldfinchFactoryAddress, data);
}
function migrateToSeniorPool(GoldfinchConfig newConfig) internal {
IMigrate(config.fiduAddress()).grantRole(MINTER_ROLE, newConfig.seniorPoolAddress());
IMigrate(config.poolAddress()).unpause();
IMigrate(newConfig.poolAddress()).migrateToSeniorPool();
}
function closeOutMigration(GoldfinchConfig newConfig) external onlyAdmin {
IMigrate fidu = IMigrate(newConfig.fiduAddress());
IMigrate creditDesk = IMigrate(newConfig.creditDeskAddress());
IMigrate oldPool = IMigrate(newConfig.poolAddress());
IMigrate goldfinchFactory = IMigrate(newConfig.goldfinchFactoryAddress());
fidu.unpause();
fidu.renounceRole(MINTER_ROLE, address(this));
fidu.renounceRole(OWNER_ROLE, address(this));
fidu.renounceRole(PAUSER_ROLE, address(this));
creditDesk.renounceRole(OWNER_ROLE, address(this));
creditDesk.renounceRole(PAUSER_ROLE, address(this));
oldPool.renounceRole(OWNER_ROLE, address(this));
oldPool.renounceRole(PAUSER_ROLE, address(this));
goldfinchFactory.renounceRole(OWNER_ROLE, address(this));
goldfinchFactory.renounceRole(PAUSER_ROLE, address(this));
config.renounceRole(PAUSER_ROLE, address(this));
config.renounceRole(OWNER_ROLE, address(this));
newConfig.renounceRole(OWNER_ROLE, address(this));
newConfig.renounceRole(PAUSER_ROLE, address(this));
newConfig.renounceRole(GO_LISTER_ROLE, address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
abstract contract IMigrate {
function pause() public virtual;
function unpause() public virtual;
function updateGoldfinchConfig() external virtual;
function grantRole(bytes32 role, address assignee) external virtual;
function renounceRole(bytes32 role, address self) external virtual;
// Proxy methods
function transferOwnership(address newOwner) external virtual;
function changeImplementation(address newImplementation, bytes calldata data) external virtual;
function owner() external view virtual returns (address);
// CreditDesk
function migrateV1CreditLine(
address _clToMigrate,
address borrower,
uint256 termEndTime,
uint256 nextDueTime,
uint256 interestAccruedAsOf,
uint256 lastFullPaymentTime,
uint256 totalInterestPaid
) public virtual returns (address, address);
// Pool
function migrateToSeniorPool() external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/Pool.sol";
contract TestPool is Pool {
function _getNumShares(uint256 amount) public view returns (uint256) {
return getNumShares(amount);
}
function _usdcMantissa() public pure returns (uint256) {
return usdcMantissa();
}
function _fiduMantissa() public pure returns (uint256) {
return fiduMantissa();
}
function _usdcToFidu(uint256 amount) public pure returns (uint256) {
return usdcToFidu(amount);
}
function _setSharePrice(uint256 newSharePrice) public returns (uint256) {
sharePrice = newSharePrice;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/Pool.sol";
import "../protocol/core/BaseUpgradeablePausable.sol";
contract FakeV2CreditLine is BaseUpgradeablePausable {
// Credit line terms
address public borrower;
address public underwriter;
uint256 public limit;
uint256 public interestApr;
uint256 public paymentPeriodInDays;
uint256 public termInDays;
uint256 public lateFeeApr;
// Accounting variables
uint256 public balance;
uint256 public interestOwed;
uint256 public principalOwed;
uint256 public termEndTime;
uint256 public nextDueTime;
uint256 public interestAccruedAsOf;
uint256 public writedownAmount;
uint256 public lastFullPaymentTime;
function initialize(
address owner,
address _borrower,
address _underwriter,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr
) public initializer {
__BaseUpgradeablePausable__init(owner);
borrower = _borrower;
underwriter = _underwriter;
limit = _limit;
interestApr = _interestApr;
paymentPeriodInDays = _paymentPeriodInDays;
termInDays = _termInDays;
lateFeeApr = _lateFeeApr;
interestAccruedAsOf = block.timestamp;
}
function anotherNewFunction() external pure returns (uint256) {
return 42;
}
function authorizePool(address) external view onlyAdmin {
// no-op
return;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
import "../../interfaces/IGo.sol";
import "../../interfaces/IUniqueIdentity0612.sol";
contract Go is IGo, BaseUpgradeablePausable {
address public override uniqueIdentity;
using SafeMath for uint256;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
GoldfinchConfig public legacyGoList;
uint256[11] public allIdTypes;
event GoldfinchConfigUpdated(address indexed who, address configAddress);
function initialize(
address owner,
GoldfinchConfig _config,
address _uniqueIdentity
) public initializer {
require(
owner != address(0) && address(_config) != address(0) && _uniqueIdentity != address(0),
"Owner and config and UniqueIdentity addresses cannot be empty"
);
__BaseUpgradeablePausable__init(owner);
_performUpgrade();
config = _config;
uniqueIdentity = _uniqueIdentity;
}
function updateGoldfinchConfig() external override onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
function performUpgrade() external onlyAdmin {
return _performUpgrade();
}
function _performUpgrade() internal {
allIdTypes[0] = ID_TYPE_0;
allIdTypes[1] = ID_TYPE_1;
allIdTypes[2] = ID_TYPE_2;
allIdTypes[3] = ID_TYPE_3;
allIdTypes[4] = ID_TYPE_4;
allIdTypes[5] = ID_TYPE_5;
allIdTypes[6] = ID_TYPE_6;
allIdTypes[7] = ID_TYPE_7;
allIdTypes[8] = ID_TYPE_8;
allIdTypes[9] = ID_TYPE_9;
allIdTypes[10] = ID_TYPE_10;
}
/**
* @notice sets the config that will be used as the source of truth for the go
* list instead of the config currently associated. To use the associated config for to list, set the override
* to the null address.
*/
function setLegacyGoList(GoldfinchConfig _legacyGoList) external onlyAdmin {
legacyGoList = _legacyGoList;
}
/**
* @notice Returns whether the provided account is go-listed for use of the Goldfinch protocol
* for any of the UID token types.
* This status is defined as: whether `balanceOf(account, id)` on the UniqueIdentity
* contract is non-zero (where `id` is a supported token id on UniqueIdentity), falling back to the
* account's status on the legacy go-list maintained on GoldfinchConfig.
* @param account The account whose go status to obtain
* @return The account's go status
*/
function go(address account) public view override returns (bool) {
require(account != address(0), "Zero address is not go-listed");
if (_getLegacyGoList().goList(account) || IUniqueIdentity0612(uniqueIdentity).balanceOf(account, ID_TYPE_0) > 0) {
return true;
}
// start loop at index 1 because we checked index 0 above
for (uint256 i = 1; i < allIdTypes.length; ++i) {
uint256 idTypeBalance = IUniqueIdentity0612(uniqueIdentity).balanceOf(account, allIdTypes[i]);
if (idTypeBalance > 0) {
return true;
}
}
return false;
}
/**
* @notice Returns whether the provided account is go-listed for use of the Goldfinch protocol
* for defined UID token types
* @param account The account whose go status to obtain
* @param onlyIdTypes Array of id types to check balances
* @return The account's go status
*/
function goOnlyIdTypes(address account, uint256[] memory onlyIdTypes) public view override returns (bool) {
require(account != address(0), "Zero address is not go-listed");
GoldfinchConfig goListSource = _getLegacyGoList();
for (uint256 i = 0; i < onlyIdTypes.length; ++i) {
if (onlyIdTypes[i] == ID_TYPE_0 && goListSource.goList(account)) {
return true;
}
uint256 idTypeBalance = IUniqueIdentity0612(uniqueIdentity).balanceOf(account, onlyIdTypes[i]);
if (idTypeBalance > 0) {
return true;
}
}
return false;
}
/**
* @notice Returns whether the provided account is go-listed for use of the SeniorPool on the Goldfinch protocol.
* @param account The account whose go status to obtain
* @return The account's go status
*/
function goSeniorPool(address account) public view override returns (bool) {
require(account != address(0), "Zero address is not go-listed");
if (account == config.stakingRewardsAddress() || _getLegacyGoList().goList(account)) {
return true;
}
uint256[2] memory seniorPoolIdTypes = [ID_TYPE_0, ID_TYPE_1];
for (uint256 i = 0; i < seniorPoolIdTypes.length; ++i) {
uint256 idTypeBalance = IUniqueIdentity0612(uniqueIdentity).balanceOf(account, seniorPoolIdTypes[i]);
if (idTypeBalance > 0) {
return true;
}
}
return false;
}
function _getLegacyGoList() internal view returns (GoldfinchConfig) {
return address(legacyGoList) == address(0) ? config : legacyGoList;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/// @dev This interface provides a subset of the functionality of the IUniqueIdentity
/// interface -- namely, the subset of functionality needed by Goldfinch protocol contracts
/// compiled with Solidity version 0.6.12.
interface IUniqueIdentity0612 {
function balanceOf(address account, uint256 id) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/GoldfinchConfig.sol";
contract TestTheConfig {
address public poolAddress = 0xBAc2781706D0aA32Fb5928c9a5191A13959Dc4AE;
address public clImplAddress = 0xc783df8a850f42e7F7e57013759C285caa701eB6;
address public goldfinchFactoryAddress = 0x0afFE1972479c386A2Ab21a27a7f835361B6C0e9;
address public fiduAddress = 0xf3c9B38c155410456b5A98fD8bBf5E35B87F6d96;
address public creditDeskAddress = 0xeAD9C93b79Ae7C1591b1FB5323BD777E86e150d4;
address public treasuryReserveAddress = 0xECd9C93B79AE7C1591b1fB5323BD777e86E150d5;
address public trustedForwarderAddress = 0x956868751Cc565507B3B58E53a6f9f41B56bed74;
address public cUSDCAddress = 0x5B281A6DdA0B271e91ae35DE655Ad301C976edb1;
address public goldfinchConfigAddress = address(8);
function testTheEnums(address configAddress) public {
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.TransactionLimit), 1);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.TotalFundsLimit), 2);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.MaxUnderwriterLimit), 3);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.ReserveDenominator), 4);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.WithdrawFeeDenominator), 5);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.LatenessGracePeriodInDays), 6);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.LatenessMaxDays), 7);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds), 8);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays), 9);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.LeverageRatio), 10);
GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.Fidu), fiduAddress);
GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.Pool), poolAddress);
GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.CreditDesk), creditDeskAddress);
GoldfinchConfig(configAddress).setAddress(
uint256(ConfigOptions.Addresses.GoldfinchFactory),
goldfinchFactoryAddress
);
GoldfinchConfig(configAddress).setAddress(
uint256(ConfigOptions.Addresses.TrustedForwarder),
trustedForwarderAddress
);
GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.CUSDCContract), cUSDCAddress);
GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.GoldfinchConfig), goldfinchConfigAddress);
GoldfinchConfig(configAddress).setTreasuryReserve(treasuryReserveAddress);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/GoldfinchConfig.sol";
contract TestGoldfinchConfig is GoldfinchConfig {
function setAddressForTest(uint256 addressKey, address newAddress) public {
addresses[addressKey] = newAddress;
}
}
|
AccreditedInvestor tokens can never be transferred. The underlying positions, however, can be transferred after the timelock expires.
|
function _beforeTokenTransfer(
address from,
address to,
) internal virtual override(ERC721PresetMinterPauserAutoIdUpgradeSafe) {
require(from == address(0) || to == address(0), "TransferRestrictedVault tokens cannot be transferred");
}
| 6,235,341 |
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/I_Token.sol
pragma solidity 0.5.0;
/**
* @title Interface Token
* @notice Allows the Curve contract to interact with the token contract
* without importing the entire smart contract. For documentation
* please see the token contract:
* https://gitlab.com/linumlabs/swarm-token
* @dev This is not a full interface of the token, but instead a partial
* interface covering only the functions that are needed by the curve.
*/
interface I_Token {
// -------------------------------------------------------------------------
// IERC20 functions
// -------------------------------------------------------------------------
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
// -------------------------------------------------------------------------
// ERC20 functions
// -------------------------------------------------------------------------
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool);
// -------------------------------------------------------------------------
// ERC20 Detailed
// -------------------------------------------------------------------------
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// -------------------------------------------------------------------------
// Burnable functions
// -------------------------------------------------------------------------
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
// -------------------------------------------------------------------------
// Mintable functions
// -------------------------------------------------------------------------
function isMinter(address account) external view returns (bool);
function addMinter(address account) external;
function renounceMinter() external;
function mint(address account, uint256 amount) external returns (bool);
// -------------------------------------------------------------------------
// Capped functions
// -------------------------------------------------------------------------
function cap() external view returns (uint256);
}
// File: contracts/I_Curve.sol
pragma solidity 0.5.0;
/**
* @title Interface Curve
* @notice This contract acts as an interface to the curve contract. For
* documentation please see the curve smart contract.
*/
interface I_Curve {
// -------------------------------------------------------------------------
// View functions
// -------------------------------------------------------------------------
/**
* @notice This function is only callable after the curve contract has been
* initialized.
* @param _amount The amount of tokens a user wants to buy
* @return uint256 The cost to buy the _amount of tokens in the collateral
* currency (see collateral token).
*/
function buyPrice(uint256 _amount)
external
view
returns (uint256 collateralRequired);
/**
* @notice This function is only callable after the curve contract has been
* initialized.
* @param _amount The amount of tokens a user wants to sell
* @return collateralReward The reward for selling the _amount of tokens in the
* collateral currency (see collateral token).
*/
function sellReward(uint256 _amount)
external
view
returns (uint256 collateralReward);
/**
* @return If the curve is both active and initialised.
*/
function isCurveActive() external view returns (bool);
/**
* @return The address of the collateral token (DAI)
*/
function collateralToken() external view returns (address);
/**
* @return The address of the bonded token (BZZ).
*/
function bondedToken() external view returns (address);
/**
* @return The required collateral amount (DAI) to initialise the curve.
*/
function requiredCollateral(uint256 _initialSupply)
external
view
returns (uint256);
// -------------------------------------------------------------------------
// State modifying functions
// -------------------------------------------------------------------------
/**
* @notice This function initializes the curve contract, and ensure the
* curve has the required permissions on the token contract needed
* to function.
*/
function init() external;
/**
* @param _amount The amount of tokens (BZZ) the user wants to buy.
* @param _maxCollateralSpend The max amount of collateral (DAI) the user is
* willing to spend in order to buy the _amount of tokens.
* @return The status of the mint. Note that should the total cost of the
* purchase exceed the _maxCollateralSpend the transaction will revert.
*/
function mint(uint256 _amount, uint256 _maxCollateralSpend)
external
returns (bool success);
/**
* @param _amount The amount of tokens (BZZ) the user wants to buy.
* @param _maxCollateralSpend The max amount of collateral (DAI) the user is
* willing to spend in order to buy the _amount of tokens.
* @param _to The address to send the tokens to.
* @return The status of the mint. Note that should the total cost of the
* purchase exceed the _maxCollateralSpend the transaction will revert.
*/
function mintTo(
uint256 _amount,
uint256 _maxCollateralSpend,
address _to
)
external
returns (bool success);
/**
* @param _amount The amount of tokens (BZZ) the user wants to sell.
* @param _minCollateralReward The min amount of collateral (DAI) the user is
* willing to receive for their tokens.
* @return The status of the burn. Note that should the total reward of the
* burn be below the _minCollateralReward the transaction will revert.
*/
function redeem(uint256 _amount, uint256 _minCollateralReward)
external
returns (bool success);
/**
* @notice Shuts down the curve, disabling buying, selling and both price
* functions. Can only be called by the owner. Will renounce the
* minter role on the bonded token.
*/
function shutDown() external;
}
// File: contracts/Curve.sol
pragma solidity 0.5.0;
contract Curve is Ownable, I_Curve {
using SafeMath for uint256;
// The instance of the token this curve controls (has mint rights to)
I_Token internal bzz_;
// The instance of the collateral token that is used to buy and sell tokens
IERC20 internal dai_;
// Stores if the curve has been initialised
bool internal init_;
// The active state of the curve (false after emergency shutdown)
bool internal active_;
// Mutex guard for state modifying functions
uint256 private status_;
// States for the guard
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
// -------------------------------------------------------------------------
// Events
// -------------------------------------------------------------------------
// Emitted when tokens are minted
event mintTokens(
address indexed buyer, // The address of the buyer
uint256 amount, // The amount of bonded tokens to mint
uint256 pricePaid, // The price in collateral tokens
uint256 maxSpend // The max amount of collateral to spend
);
// Emitted when tokens are minted
event mintTokensTo(
address indexed buyer, // The address of the buyer
address indexed receiver, // The address of the receiver of the tokens
uint256 amount, // The amount of bonded tokens to mint
uint256 pricePaid, // The price in collateral tokens
uint256 maxSpend // The max amount of collateral to spend
);
// Emitted when tokens are burnt
event burnTokens(
address indexed seller, // The address of the seller
uint256 amount, // The amount of bonded tokens to sell
uint256 rewardReceived, // The collateral tokens received
uint256 minReward // The min collateral reward for tokens
);
// Emitted when the curve is permanently shut down
event shutDownOccurred(address indexed owner);
// -------------------------------------------------------------------------
// Modifiers
// -------------------------------------------------------------------------
/**
* @notice Requires the curve to be initialised and active.
*/
modifier isActive() {
require(active_ && init_, "Curve inactive");
_;
}
/**
* @notice Protects against re-entrancy attacks
*/
modifier mutex() {
require(status_ != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
status_ = _ENTERED;
// Function executes
_;
// Status set to not entered
status_ = _NOT_ENTERED;
}
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
constructor(address _bondedToken, address _collateralToken) public Ownable() {
bzz_ = I_Token(_bondedToken);
dai_ = IERC20(_collateralToken);
status_ = _NOT_ENTERED;
}
// -------------------------------------------------------------------------
// View functions
// -------------------------------------------------------------------------
/**
* @notice This function is only callable after the curve contract has been
* initialized.
* @param _amount The amount of tokens a user wants to buy
* @return uint256 The cost to buy the _amount of tokens in the collateral
* currency (see collateral token).
*/
function buyPrice(uint256 _amount)
public
view
isActive()
returns (uint256 collateralRequired)
{
collateralRequired = _mint(_amount, bzz_.totalSupply());
return collateralRequired;
}
/**
* @notice This function is only callable after the curve contract has been
* initialized.
* @param _amount The amount of tokens a user wants to sell
* @return collateralReward The reward for selling the _amount of tokens in the
* collateral currency (see collateral token).
*/
function sellReward(uint256 _amount)
public
view
isActive()
returns (uint256 collateralReward)
{
(collateralReward, ) = _withdraw(_amount, bzz_.totalSupply());
return collateralReward;
}
/**
* @return If the curve is both active and initialised.
*/
function isCurveActive() public view returns (bool) {
if (active_ && init_) {
return true;
}
return false;
}
/**
* @param _initialSupply The expected initial supply the bonded token
* will have.
* @return The required collateral amount (DAI) to initialise the curve.
*/
function requiredCollateral(uint256 _initialSupply)
public
view
returns (uint256)
{
return _initializeCurve(_initialSupply);
}
/**
* @return The address of the bonded token (BZZ).
*/
function bondedToken() external view returns (address) {
return address(bzz_);
}
/**
* @return The address of the collateral token (DAI)
*/
function collateralToken() external view returns (address) {
return address(dai_);
}
// -------------------------------------------------------------------------
// State modifying functions
// -------------------------------------------------------------------------
/**
* @notice This function initializes the curve contract, and ensure the
* curve has the required permissions on the token contract needed
* to function.
*/
function init() external {
// Checks the curve has not already been initialized
require(!init_, "Curve is init");
// Checks the curve has the correct permissions on the given token
require(bzz_.isMinter(address(this)), "Curve is not minter");
// Gets the total supply of the token
uint256 initialSupply = bzz_.totalSupply();
// The curve requires that the initial supply is at least the expected
// open market supply
require(
initialSupply >= _MARKET_OPENING_SUPPLY,
"Curve equation requires pre-mint"
);
// Gets the price for the current supply
uint256 price = _initializeCurve(initialSupply);
// Requires the transfer for the collateral needed to back fill for the
// minted supply
require(
dai_.transferFrom(msg.sender, address(this), price),
"Failed to collateralized the curve"
);
// Sets the Curve to being active and initialised
active_ = true;
init_ = true;
}
/**
* @param _amount The amount of tokens (BZZ) the user wants to buy.
* @param _maxCollateralSpend The max amount of collateral (DAI) the user is
* willing to spend in order to buy the _amount of tokens.
* @return The status of the mint. Note that should the total cost of the
* purchase exceed the _maxCollateralSpend the transaction will revert.
*/
function mint(
uint256 _amount,
uint256 _maxCollateralSpend
)
external
isActive()
mutex()
returns (bool success)
{
// Gets the price for the amount of tokens
uint256 price = _commonMint(_amount, _maxCollateralSpend, msg.sender);
// Emitting event with all important info
emit mintTokens(
msg.sender,
_amount,
price,
_maxCollateralSpend
);
// Returning that the mint executed successfully
return true;
}
/**
* @param _amount The amount of tokens (BZZ) the user wants to buy.
* @param _maxCollateralSpend The max amount of collateral (DAI) the user is
* willing to spend in order to buy the _amount of tokens.
* @param _to The address to send the tokens to.
* @return The status of the mint. Note that should the total cost of the
* purchase exceed the _maxCollateralSpend the transaction will revert.
*/
function mintTo(
uint256 _amount,
uint256 _maxCollateralSpend,
address _to
)
external
isActive()
mutex()
returns (bool success)
{
// Gets the price for the amount of tokens
uint256 price = _commonMint(_amount, _maxCollateralSpend, _to);
// Emitting event with all important info
emit mintTokensTo(
msg.sender,
_to,
_amount,
price,
_maxCollateralSpend
);
// Returning that the mint executed successfully
return true;
}
/**
* @param _amount The amount of tokens (BZZ) the user wants to sell.
* @param _minCollateralReward The min amount of collateral (DAI) the user is
* willing to receive for their tokens.
* @return The status of the burn. Note that should the total reward of the
* burn be below the _minCollateralReward the transaction will revert.
*/
function redeem(uint256 _amount, uint256 _minCollateralReward)
external
isActive()
mutex()
returns (bool success)
{
// Gets the reward for the amount of tokens
uint256 reward = sellReward(_amount);
// Checks the reward has not slipped below the min amount the user
// wishes to receive.
require(reward >= _minCollateralReward, "Reward under min sell");
// Burns the number of tokens (fails - no bool return)
bzz_.burnFrom(msg.sender, _amount);
// Transfers the reward from the curve to the collateral token
require(
dai_.transfer(msg.sender, reward),
"Transferring collateral failed"
);
// Emitting event with all important info
emit burnTokens(
msg.sender,
_amount,
reward,
_minCollateralReward
);
// Returning that the burn executed successfully
return true;
}
/**
* @notice Shuts down the curve, disabling buying, selling and both price
* functions. Can only be called by the owner. Will renounce the
* minter role on the bonded token.
*/
function shutDown() external onlyOwner() {
// Removes the curve as a minter on the token
bzz_.renounceMinter();
// Irreversibly shuts down the curve
active_ = false;
// Emitting address of owner who shut down curve permanently
emit shutDownOccurred(msg.sender);
}
// -------------------------------------------------------------------------
// Internal functions
// -------------------------------------------------------------------------
/**
* @param _amount The amount of tokens (BZZ) the user wants to buy.
* @param _maxCollateralSpend The max amount of collateral (DAI) the user is
* willing to spend in order to buy the _amount of tokens.
* @param _to The address to send the tokens to.
* @return uint256 The price the user has paid for buying the _amount of
* BUZZ tokens.
*/
function _commonMint(
uint256 _amount,
uint256 _maxCollateralSpend,
address _to
)
internal
returns(uint256)
{
// Gets the price for the amount of tokens
uint256 price = buyPrice(_amount);
// Checks the price has not risen above the max amount the user wishes
// to spend.
require(price <= _maxCollateralSpend, "Price exceeds max spend");
// Transfers the price of tokens in the collateral token to the curve
require(
dai_.transferFrom(msg.sender, address(this), price),
"Transferring collateral failed"
);
// Mints the user their tokens
require(bzz_.mint(_to, _amount), "Minting tokens failed");
// Returns the price the user will pay for buy
return price;
}
// -------------------------------------------------------------------------
// Curve mathematical functions
uint256 internal constant _BZZ_SCALE = 1e16;
uint256 internal constant _N = 5;
uint256 internal constant _MARKET_OPENING_SUPPLY = 62500000 * _BZZ_SCALE;
// Equation for curve:
/**
* @param x The supply to calculate at.
* @return x^32/_MARKET_OPENING_SUPPLY^5
* @dev Calculates the 32 power of `x` (`x` squared 5 times) times a
* constant. Each time it squares the function it divides by the
* `_MARKET_OPENING_SUPPLY` so when `x` = `_MARKET_OPENING_SUPPLY`
* it doesn't change `x`.
*
* `c*x^32` | `c` is chosen in such a way that
* `_MARKET_OPENING_SUPPLY` is the fixed point of the helper
* function.
*
* The division by `_MARKET_OPENING_SUPPLY` also helps avoid an
* overflow.
*
* The `_helper` function is separate to the `_primitiveFunction`
* as we modify `x`.
*/
function _helper(uint256 x) internal view returns (uint256) {
for (uint256 index = 1; index <= _N; index++) {
x = (x.mul(x)).div(_MARKET_OPENING_SUPPLY);
}
return x;
}
/**
* @param s The supply point being calculated for.
* @return The amount of DAI required for the requested amount of BZZ (s).
* @dev `s` is being added because it is the linear term in the
* polynomial (this ensures no free BUZZ tokens).
*
* primitive function equation: s + c*s^32.
*
* See the helper function for the definition of `c`.
*
* Converts from something measured in BZZ (1e16) to dai atomic
* units 1e18.
*/
function _primitiveFunction(uint256 s) internal view returns (uint256) {
return s.add(_helper(s));
}
/**
* @param _supply The number of tokens that exist.
* @return uint256 The price for the next token up the curve.
*/
function _spotPrice(uint256 _supply) internal view returns (uint256) {
return (_primitiveFunction(_supply.add(1)).sub(_primitiveFunction(_supply)));
}
/**
* @param _amount The amount of tokens to be minted
* @param _currentSupply The current supply of tokens
* @return uint256 The cost for the tokens
* @return uint256 The price being paid per token
*/
function _mint(uint256 _amount, uint256 _currentSupply)
internal
view
returns (uint256)
{
uint256 deltaR = _primitiveFunction(_currentSupply.add(_amount)).sub(
_primitiveFunction(_currentSupply));
return deltaR;
}
/**
* @param _amount The amount of tokens to be sold
* @param _currentSupply The current supply of tokens
* @return uint256 The reward for the tokens
* @return uint256 The price being received per token
*/
function _withdraw(uint256 _amount, uint256 _currentSupply)
internal
view
returns (uint256, uint256)
{
assert(_currentSupply - _amount > 0);
uint256 deltaR = _primitiveFunction(_currentSupply).sub(
_primitiveFunction(_currentSupply.sub(_amount)));
uint256 realized_price = deltaR.div(_amount);
return (deltaR, realized_price);
}
/**
* @param _initial_supply The supply the curve is going to start with.
* @return initial_reserve How much collateral is needed to collateralized
* the bonding curve.
* @return price The price being paid per token (averaged).
*/
function _initializeCurve(uint256 _initial_supply)
internal
view
returns (uint256 price)
{
price = _mint(_initial_supply, 0);
return price;
}
}
|
return The address of the collateral token (DAI)/
|
function collateralToken() external view returns (address) {
return address(dai_);
}
| 1,824,489 |
pragma solidity ^0.4.18;
// File: contracts/flavours/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: contracts/commons/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts/flavours/Lockable.sol
/**
* @title Lockable
* @dev Base contract which allows children to
* implement main operations locking mechanism.
*/
contract Lockable is Ownable {
event Lock();
event Unlock();
bool public locked = false;
/**
* @dev Modifier to make a function callable
* only when the contract is not locked.
*/
modifier whenNotLocked() {
require(!locked);
_;
}
/**
* @dev Modifier to make a function callable
* only when the contract is locked.
*/
modifier whenLocked() {
require(locked);
_;
}
/**
* @dev called by the owner to locke, triggers locked state
*/
function lock() onlyOwner whenNotLocked public {
locked = true;
Lock();
}
/**
* @dev called by the owner
* to unlock, returns to unlocked state
*/
function unlock() onlyOwner whenLocked public {
locked = false;
Unlock();
}
}
// File: contracts/base/BaseFixedERC20Token.sol
contract BaseFixedERC20Token is Lockable {
using SafeMath for uint;
/// @dev ERC20 Total supply
uint public totalSupply;
mapping(address => uint) balances;
mapping(address => mapping (address => uint)) private allowed;
/// @dev Fired if Token transfered accourding to ERC20
event Transfer(address indexed from, address indexed to, uint value);
/// @dev Fired if Token withdraw is approved accourding to ERC20
event Approval(address indexed owner, address indexed spender, uint value);
/**
* @dev Gets the balance of the specified address.
* @param owner_ The address to query the the balance of.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address owner_) public view returns (uint balance) {
return balances[owner_];
}
/**
* @dev Transfer token for a specified address
* @param to_ The address to transfer to.
* @param value_ The amount to be transferred.
*/
function transfer(address to_, uint value_) whenNotLocked public returns (bool) {
require(to_ != address(0) && value_ <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(value_);
balances[to_] = balances[to_].add(value_);
Transfer(msg.sender, to_, value_);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from_ address The address which you want to send tokens from
* @param to_ address The address which you want to transfer to
* @param value_ uint the amount of tokens to be transferred
*/
function transferFrom(address from_, address to_, uint value_) whenNotLocked public returns (bool) {
require(to_ != address(0) && value_ <= balances[from_] && value_ <= allowed[from_][msg.sender]);
balances[from_] = balances[from_].sub(value_);
balances[to_] = balances[to_].add(value_);
allowed[from_][msg.sender] = allowed[from_][msg.sender].sub(value_);
Transfer(from_, to_, value_);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering.
*
* To change the approve amount you first have to reduce the addresses
* allowance to zero by calling `approve(spender_, 0)` if it is not
* already 0 to mitigate the race condition described in:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* @param spender_ The address which will spend the funds.
* @param value_ The amount of tokens to be spent.
*/
function approve(address spender_, uint value_) whenNotLocked public returns (bool) {
if (value_ != 0 && allowed[msg.sender][spender_] != 0) {
revert();
}
allowed[msg.sender][spender_] = value_;
Approval(msg.sender, spender_, value_);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner_ address The address which owns the funds.
* @param spender_ address The address which will spend the funds.
* @return A uint specifying the amount of tokens still available for the spender.
*/
function allowance(address owner_, address spender_) view public returns (uint) {
return allowed[owner_][spender_];
}
}
// File: contracts/base/BaseICOToken.sol
/**
* @dev Not mintable, ERC20 compilant token, distributed by ICO/Pre-ICO.
*/
contract BaseICOToken is BaseFixedERC20Token {
/// @dev Available supply of tokens
uint public availableSupply;
/// @dev ICO/Pre-ICO smart contract allowed to distribute public funds for this
address public ico;
/// @dev Fired if investment for `amount` of tokens performed by `to` address
event ICOTokensInvested(address indexed to, uint amount);
/// @dev ICO contract changed for this token
event ICOChanged(address indexed icoContract);
/**
* @dev Not mintable, ERC20 compilant token, distributed by ICO/Pre-ICO.
* @param totalSupply_ Total tokens supply.
*/
function BaseICOToken(uint totalSupply_) public {
locked = true;
totalSupply = totalSupply_;
availableSupply = totalSupply_;
}
/**
* @dev Set address of ICO smart-contract which controls token
* initial token distribution.
* @param ico_ ICO contract address.
*/
function changeICO(address ico_) onlyOwner public {
ico = ico_;
ICOChanged(ico);
}
function isValidICOInvestment(address to_, uint amount_) internal view returns(bool) {
return msg.sender == ico && to_ != address(0) && amount_ <= availableSupply;
}
/**
* @dev Assign `amount_` of tokens to investor identified by `to_` address.
* @param to_ Investor address.
* @param amount_ Number of tokens distributed.
*/
function icoInvestment(address to_, uint amount_) public returns (uint) {
require(isValidICOInvestment(to_, amount_));
availableSupply -= amount_;
balances[to_] = balances[to_].add(amount_);
ICOTokensInvested(to_, amount_);
return amount_;
}
}
// File: contracts/base/BaseICO.sol
/**
* @dev Base abstract smart contract for any ICO
*/
contract BaseICO is Ownable {
/// @dev ICO state
enum State {
// ICO is not active and not started
Inactive,
// ICO is active, tokens can be distributed among investors.
// ICO parameters (end date, hard/low caps) cannot be changed.
Active,
// ICO is suspended, tokens cannot be distributed among investors.
// ICO can be resumed to `Active state`.
// ICO parameters (end date, hard/low caps) may changed.
Suspended,
// ICO is termnated by owner, ICO cannot be resumed.
Terminated,
// ICO goals are not reached,
// ICO terminated and cannot be resumed.
NotCompleted,
// ICO completed, ICO goals reached successfully,
// ICO terminated and cannot be resumed.
Completed
}
/// @dev Token which controlled by this ICO
BaseICOToken public token;
/// @dev Current ICO state.
State public state;
/// @dev ICO start date seconds since epoch.
uint public startAt;
/// @dev ICO end date seconds since epoch.
uint public endAt;
/// @dev Minimal amount of investments in wei needed for successfull ICO
uint public lowCapWei;
/// @dev Maximal amount of investments in wei for this ICO.
/// If reached ICO will be in `Completed` state.
uint public hardCapWei;
/// @dev Minimal amount of investments in wei per investor.
uint public lowCapTxWei;
/// @dev Maximal amount of investments in wei per investor.
uint public hardCapTxWei;
/// @dev Number of investments collected by this ICO
uint public collectedWei;
/// @dev Team wallet used to collect funds
address public teamWallet;
/// @dev True if whitelist enabled
bool public whitelistEnabled = true;
/// @dev ICO whitelist
mapping (address => bool) public whitelist;
// ICO state transition events
event ICOStarted(uint indexed endAt, uint lowCapWei, uint hardCapWei, uint lowCapTxWei, uint hardCapTxWei);
event ICOResumed(uint indexed endAt, uint lowCapWei, uint hardCapWei, uint lowCapTxWei, uint hardCapTxWei);
event ICOSuspended();
event ICOTerminated();
event ICONotCompleted();
event ICOCompleted(uint collectedWei);
event ICOInvestment(address indexed from, uint investedWei, uint tokens, uint8 bonusPct);
event ICOWhitelisted(address indexed addr);
event ICOBlacklisted(address indexed addr);
modifier isSuspended() {
require(state == State.Suspended);
_;
}
modifier isActive() {
require(state == State.Active);
_;
}
/**
* Add address to ICO whitelist
* @param address_ Investor address
*/
function whitelist(address address_) external onlyOwner {
whitelist[address_] = true;
ICOWhitelisted(address_);
}
/**
* Remove address from ICO whitelist
* @param address_ Investor address
*/
function blacklist(address address_) external onlyOwner {
delete whitelist[address_];
ICOBlacklisted(address_);
}
/**
* @dev Returns true if given address in ICO whitelist
*/
function whitelisted(address address_) public view returns (bool) {
if (whitelistEnabled) {
return whitelist[address_];
} else {
return true;
}
}
/**
* @dev Enable whitelisting
*/
function enableWhitelist() public onlyOwner {
whitelistEnabled = true;
}
/**
* @dev Disable whitelisting
*/
function disableWhitelist() public onlyOwner {
whitelistEnabled = false;
}
/**
* @dev Trigger start of ICO.
* @param endAt_ ICO end date, seconds since epoch.
*/
function start(uint endAt_) onlyOwner public {
require(endAt_ > block.timestamp && state == State.Inactive);
endAt = endAt_;
startAt = block.timestamp;
state = State.Active;
ICOStarted(endAt, lowCapWei, hardCapWei, lowCapTxWei, hardCapTxWei);
}
/**
* @dev Suspend this ICO.
* ICO can be activated later by calling `resume()` function.
* In suspend state, ICO owner can change basic ICO paraneter using `tune()` function,
* tokens cannot be distributed among investors.
*/
function suspend() onlyOwner isActive public {
state = State.Suspended;
ICOSuspended();
}
/**
* @dev Terminate the ICO.
* ICO goals are not reached, ICO terminated and cannot be resumed.
*/
function terminate() onlyOwner public {
require(state != State.Terminated &&
state != State.NotCompleted &&
state != State.Completed);
state = State.Terminated;
ICOTerminated();
}
/**
* @dev Change basic ICO paraneters. Can be done only during `Suspended` state.
* Any provided parameter is used only if it is not zero.
* @param endAt_ ICO end date seconds since epoch. Used if it is not zero.
* @param lowCapWei_ ICO low capacity. Used if it is not zero.
* @param hardCapWei_ ICO hard capacity. Used if it is not zero.
* @param lowCapTxWei_ Min limit for ICO per transaction
* @param hardCapTxWei_ Hard limit for ICO per transaction
*/
function tune(uint endAt_,
uint lowCapWei_,
uint hardCapWei_,
uint lowCapTxWei_,
uint hardCapTxWei_) onlyOwner isSuspended public {
if (endAt_ > block.timestamp) {
endAt = endAt_;
}
if (lowCapWei_ > 0) {
lowCapWei = lowCapWei_;
}
if (hardCapWei_ > 0) {
hardCapWei = hardCapWei_;
}
if (lowCapTxWei_ > 0) {
lowCapTxWei = lowCapTxWei_;
}
if (hardCapTxWei_ > 0) {
hardCapTxWei = hardCapTxWei_;
}
require(lowCapWei <= hardCapWei && lowCapTxWei <= hardCapTxWei);
touch();
}
/**
* @dev Resume a previously suspended ICO.
*/
function resume() onlyOwner isSuspended public {
state = State.Active;
ICOResumed(endAt, lowCapWei, hardCapWei, lowCapTxWei, hardCapTxWei);
touch();
}
/**
* @dev Send ether to the fund collection wallet
*/
function forwardFunds() internal {
teamWallet.transfer(msg.value);
}
/**
* @dev Recalculate ICO state based on current block time.
* Should be called periodically by ICO owner.
*/
function touch() public;
/**
* @dev Buy tokens
*/
function buyTokens() public payable;
}
// File: contracts/MDICOStage1.sol
/**
* @title MD tokens ICO Stage 1 contract.
*/
contract MDICOStage1 is BaseICO {
using SafeMath for uint;
/// @dev 18 decimals for token
uint internal constant ONE_TOKEN = 1e18;
/// @dev 1e18 WEI == 1ETH == 1000 tokens
uint public constant ETH_TOKEN_EXCHANGE_RATIO = 1000;
/// @dev 50% bonus for ICO Stage 1
uint8 internal constant BONUS = 50; // 50%
function MDICOStage1(address icoToken_,
address teamWallet_,
uint lowCapWei_,
uint hardCapWei_,
uint lowCapTxWei_,
uint hardCapTxWei_) public {
require(icoToken_ != address(0) && teamWallet_ != address(0));
token = BaseICOToken(icoToken_);
teamWallet = teamWallet_;
state = State.Inactive;
lowCapWei = lowCapWei_;
hardCapWei = hardCapWei_;
lowCapTxWei = lowCapTxWei_;
hardCapTxWei = hardCapTxWei_;
}
/**
* @dev Recalculate ICO state based on current block time.
* Should be called periodically by ICO owner.
*/
function touch() public {
if (state != State.Active && state != State.Suspended) {
return;
}
if (collectedWei >= hardCapWei) {
state = State.Completed;
endAt = block.timestamp;
ICOCompleted(collectedWei);
} else if (block.timestamp >= endAt) {
if (collectedWei < lowCapWei) {
state = State.NotCompleted;
ICONotCompleted();
} else {
state = State.Completed;
ICOCompleted(collectedWei);
}
}
}
function buyTokens() public payable {
require(state == State.Active &&
block.timestamp <= endAt &&
msg.value >= lowCapTxWei &&
msg.value <= hardCapTxWei &&
collectedWei + msg.value <= hardCapWei &&
whitelisted(msg.sender));
uint amountWei = msg.value;
uint iwei = amountWei.mul(100 + BONUS).div(100);
uint itokens = iwei * ETH_TOKEN_EXCHANGE_RATIO;
token.icoInvestment(msg.sender, itokens); // Transfer tokens to investor
collectedWei = collectedWei.add(amountWei);
ICOInvestment(msg.sender, amountWei, itokens, BONUS);
forwardFunds();
touch();
}
/**
* Accept direct payments
*/
function() external payable {
buyTokens();
}
}
|
Enable whitelisting/
|
function enableWhitelist() public onlyOwner {
whitelistEnabled = true;
}
| 6,691,158 |
pragma solidity ^0.4.24;
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
library UrlStr {
// generate url by tokenId
// baseUrl must end with 00000000
function generateUrl(string url,uint256 _tokenId) internal pure returns (string _url){
_url = url;
bytes memory _tokenURIBytes = bytes(_url);
uint256 base_len = _tokenURIBytes.length - 1;
_tokenURIBytes[base_len - 7] = byte(48 + _tokenId / 10000000 % 10);
_tokenURIBytes[base_len - 6] = byte(48 + _tokenId / 1000000 % 10);
_tokenURIBytes[base_len - 5] = byte(48 + _tokenId / 100000 % 10);
_tokenURIBytes[base_len - 4] = byte(48 + _tokenId / 10000 % 10);
_tokenURIBytes[base_len - 3] = byte(48 + _tokenId / 1000 % 10);
_tokenURIBytes[base_len - 2] = byte(48 + _tokenId / 100 % 10);
_tokenURIBytes[base_len - 1] = byte(48 + _tokenId / 10 % 10);
_tokenURIBytes[base_len - 0] = byte(48 + _tokenId / 1 % 10);
}
}
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId) external view returns (bool);
}
interface ERC721 /* is ERC165 */ {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) external view returns (uint256);
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId) external view returns (address);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId) external;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
/// Note: the ERC-165 identifier for this interface is 0x780e9d63.
interface ERC721Enumerable /* is ERC721 */ {
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() external view returns (uint256);
/// @notice Enumerate valid NFTs
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for the `_index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 _index) external view returns (uint256);
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
}
/// Note: the ERC-165 identifier for this interface is 0x5b5e139f.
interface ERC721Metadata /* is ERC721 */ {
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string _name);
/// @notice An abbreviated name for NFTs in this contract
function symbol() external view returns (string _symbol);
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
/// 3986. The URI may point to a JSON file that conforms to the "ERC721
/// Metadata JSON Schema".
function tokenURI(uint256 _tokenId) external view returns (string);
}
/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02.
interface ERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
/// transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _operator The address which called `safeTransferFrom` function
/// @param _from The address which previously owned the token
/// @param _tokenId The NFT identifier which is being transferred
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
/// unless throwing
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4);
}
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
public
{
_registerInterface(InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId)
internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title Operator
* @dev Allow two roles: 'owner' or 'operator'
* - owner: admin/superuser (e.g. with financial rights)
* - operator: can update configurations
*/
contract Operator is Ownable {
address[] public operators;
uint public MAX_OPS = 20; // Default maximum number of operators allowed
mapping(address => bool) public isOperator;
event OperatorAdded(address operator);
event OperatorRemoved(address operator);
// @dev Throws if called by any non-operator account. Owner has all ops rights.
modifier onlyOperator() {
require(
isOperator[msg.sender] || msg.sender == owner,
"Permission denied. Must be an operator or the owner."
);
_;
}
/**
* @dev Allows the current owner or operators to add operators
* @param _newOperator New operator address
*/
function addOperator(address _newOperator) public onlyOwner {
require(
_newOperator != address(0),
"Invalid new operator address."
);
// Make sure no dups
require(
!isOperator[_newOperator],
"New operator exists."
);
// Only allow so many ops
require(
operators.length < MAX_OPS,
"Overflow."
);
operators.push(_newOperator);
isOperator[_newOperator] = true;
emit OperatorAdded(_newOperator);
}
/**
* @dev Allows the current owner or operators to remove operator
* @param _operator Address of the operator to be removed
*/
function removeOperator(address _operator) public onlyOwner {
// Make sure operators array is not empty
require(
operators.length > 0,
"No operator."
);
// Make sure the operator exists
require(
isOperator[_operator],
"Not an operator."
);
// Manual array manipulation:
// - replace the _operator with last operator in array
// - remove the last item from array
address lastOperator = operators[operators.length - 1];
for (uint i = 0; i < operators.length; i++) {
if (operators[i] == _operator) {
operators[i] = lastOperator;
}
}
operators.length -= 1; // remove the last element
isOperator[_operator] = false;
emit OperatorRemoved(_operator);
}
// @dev Remove ALL operators
function removeAllOps() public onlyOwner {
for (uint i = 0; i < operators.length; i++) {
isOperator[operators[i]] = false;
}
operators.length = 0;
}
}
contract Pausable is Operator {
event FrozenFunds(address target, bool frozen);
bool public isPaused = false;
mapping(address => bool) frozenAccount;
modifier whenNotPaused {
require(!isPaused);
_;
}
modifier whenPaused {
require(isPaused);
_;
}
modifier whenNotFreeze(address _target) {
require(_target != address(0));
require(!frozenAccount[_target]);
_;
}
function isFrozen(address _target) external view returns (bool) {
require(_target != address(0));
return frozenAccount[_target];
}
function doPause() external whenNotPaused onlyOwner {
isPaused = true;
}
function doUnpause() external whenPaused onlyOwner {
isPaused = false;
}
function freezeAccount(address _target, bool _freeze) public onlyOwner {
require(_target != address(0));
frozenAccount[_target] = _freeze;
emit FrozenFunds(_target, _freeze);
}
}
interface ERC998ERC721TopDown {
event ReceivedChild(address indexed _from, uint256 indexed _tokenId, address indexed _childContract, uint256 _childTokenId);
event TransferChild(uint256 indexed tokenId, address indexed _to, address indexed _childContract, uint256 _childTokenId);
function rootOwnerOf(uint256 _tokenId) external view returns (bytes32 rootOwner);
function rootOwnerOfChild(address _childContract, uint256 _childTokenId) external view returns (bytes32 rootOwner);
function ownerOfChild(address _childContract, uint256 _childTokenId) external view returns (bytes32 parentTokenOwner, uint256 parentTokenId);
function onERC721Received(address _operator, address _from, uint256 _childTokenId, bytes _data) external returns (bytes4);
function transferChild(uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId) external;
function safeTransferChild(uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId) external;
function safeTransferChild(uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId, bytes _data) external;
function transferChildToParent(uint256 _fromTokenId, address _toContract, uint256 _toTokenId, address _childContract, uint256 _childTokenId, bytes _data) external;
// getChild function enables older contracts like cryptokitties to be transferred into a composable
// The _childContract must approve this contract. Then getChild can be called.
function getChild(address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId) external;
}
interface ERC998ERC721TopDownEnumerable {
function totalChildContracts(uint256 _tokenId) external view returns (uint256);
function childContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address childContract);
function totalChildTokens(uint256 _tokenId, address _childContract) external view returns (uint256);
function childTokenByIndex(uint256 _tokenId, address _childContract, uint256 _index) external view returns (uint256 childTokenId);
}
interface ERC998ERC20TopDown {
event ReceivedERC20(address indexed _from, uint256 indexed _tokenId, address indexed _erc20Contract, uint256 _value);
event TransferERC20(uint256 indexed _tokenId, address indexed _to, address indexed _erc20Contract, uint256 _value);
function tokenFallback(address _from, uint256 _value, bytes _data) external;
function balanceOfERC20(uint256 _tokenId, address __erc20Contract) external view returns (uint256);
function transferERC20(uint256 _tokenId, address _to, address _erc20Contract, uint256 _value) external;
function transferERC223(uint256 _tokenId, address _to, address _erc223Contract, uint256 _value, bytes _data) external;
function getERC20(address _from, uint256 _tokenId, address _erc20Contract, uint256 _value) external;
}
interface ERC998ERC20TopDownEnumerable {
function totalERC20Contracts(uint256 _tokenId) external view returns (uint256);
function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address);
}
interface ERC20AndERC223 {
function transferFrom(address _from, address _to, uint _value) external returns (bool success);
function transfer(address to, uint value) external returns (bool success);
function transfer(address to, uint value, bytes data) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
}
interface ERC998ERC721BottomUp {
function transferToParent(address _from, address _toContract, uint256 _toTokenId, uint256 _tokenId, bytes _data) external;
}
contract ComposableTopDown is Pausable, ERC721, ERC998ERC721TopDown, ERC998ERC721TopDownEnumerable,
ERC998ERC20TopDown, ERC998ERC20TopDownEnumerable {
// return this.rootOwnerOf.selector ^ this.rootOwnerOfChild.selector ^
// this.tokenOwnerOf.selector ^ this.ownerOfChild.selector;
bytes32 constant ERC998_MAGIC_VALUE = 0xcd740db5;
// tokenId => token owner
mapping(uint256 => address) internal tokenIdToTokenOwner;
// root token owner address => (tokenId => approved address)
mapping(address => mapping(uint256 => address)) internal rootOwnerAndTokenIdToApprovedAddress;
// token owner address => token count
mapping(address => uint256) internal tokenOwnerToTokenCount;
// token owner => (operator address => bool)
mapping(address => mapping(address => bool)) internal tokenOwnerToOperators;
//constructor(string _name, string _symbol) public ERC721Token(_name, _symbol) {}
function _mint(address _to,uint256 _tokenId) internal whenNotPaused {
tokenIdToTokenOwner[_tokenId] = _to;
tokenOwnerToTokenCount[_to]++;
emit Transfer(address(0), _to, _tokenId);
}
//from zepellin ERC721Receiver.sol
//old version
bytes4 constant ERC721_RECEIVED_OLD = 0xf0b9e5ba;
//new version
bytes4 constant ERC721_RECEIVED_NEW = 0x150b7a02;
////////////////////////////////////////////////////////
// ERC721 implementation
////////////////////////////////////////////////////////
function isContract(address _addr) internal view returns (bool) {
uint256 size;
assembly {size := extcodesize(_addr)}
return size > 0;
}
function rootOwnerOf(uint256 _tokenId) public view returns (bytes32 rootOwner) {
return rootOwnerOfChild(address(0), _tokenId);
}
// returns the owner at the top of the tree of composables
// Use Cases handled:
// Case 1: Token owner is this contract and token.
// Case 2: Token owner is other top-down composable
// Case 3: Token owner is other contract
// Case 4: Token owner is user
function rootOwnerOfChild(address _childContract, uint256 _childTokenId) public view returns (bytes32 rootOwner) {
address rootOwnerAddress;
if (_childContract != address(0)) {
(rootOwnerAddress, _childTokenId) = _ownerOfChild(_childContract, _childTokenId);
}
else {
rootOwnerAddress = tokenIdToTokenOwner[_childTokenId];
}
// Case 1: Token owner is this contract and token.
while (rootOwnerAddress == address(this)) {
(rootOwnerAddress, _childTokenId) = _ownerOfChild(rootOwnerAddress, _childTokenId);
}
bool callSuccess;
bytes memory calldata;
// 0xed81cdda == rootOwnerOfChild(address,uint256)
calldata = abi.encodeWithSelector(0xed81cdda, address(this), _childTokenId);
assembly {
callSuccess := staticcall(gas, rootOwnerAddress, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
}
if(callSuccess == true && rootOwner >> 224 == ERC998_MAGIC_VALUE) {
// Case 2: Token owner is other top-down composable
return rootOwner;
}
else {
// Case 3: Token owner is other contract
// Or
// Case 4: Token owner is user
return ERC998_MAGIC_VALUE << 224 | bytes32(rootOwnerAddress);
}
}
// returns the owner at the top of the tree of composables
function ownerOf(uint256 _tokenId) public view returns (address tokenOwner) {
tokenOwner = tokenIdToTokenOwner[_tokenId];
require(tokenOwner != address(0));
return tokenOwner;
}
function balanceOf(address _tokenOwner) external view returns (uint256) {
require(_tokenOwner != address(0));
return tokenOwnerToTokenCount[_tokenOwner];
}
function approve(address _approved, uint256 _tokenId) external whenNotPaused {
address rootOwner = address(rootOwnerOf(_tokenId));
require(rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender]);
rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] = _approved;
emit Approval(rootOwner, _approved, _tokenId);
}
function getApproved(uint256 _tokenId) public view returns (address) {
address rootOwner = address(rootOwnerOf(_tokenId));
return rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId];
}
function setApprovalForAll(address _operator, bool _approved) external whenNotPaused {
require(_operator != address(0));
tokenOwnerToOperators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
function isApprovedForAll(address _owner, address _operator) external view returns (bool) {
require(_owner != address(0));
require(_operator != address(0));
return tokenOwnerToOperators[_owner][_operator];
}
function _transferFrom(address _from, address _to, uint256 _tokenId) internal whenNotPaused {
require(_from != address(0));
require(tokenIdToTokenOwner[_tokenId] == _from);
require(_to != address(0));
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
if(msg.sender != _from) {
bytes32 rootOwner;
bool callSuccess;
// 0xed81cdda == rootOwnerOfChild(address,uint256)
bytes memory calldata = abi.encodeWithSelector(0xed81cdda, address(this), _tokenId);
assembly {
callSuccess := staticcall(gas, _from, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
}
if(callSuccess == true) {
require(rootOwner >> 224 != ERC998_MAGIC_VALUE, "Token is child of other top down composable");
}
require(tokenOwnerToOperators[_from][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId] == msg.sender);
}
// clear approval
if (rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId] != address(0)) {
delete rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId];
emit Approval(_from, address(0), _tokenId);
}
// remove and transfer token
if (_from != _to) {
assert(tokenOwnerToTokenCount[_from] > 0);
tokenOwnerToTokenCount[_from]--;
tokenIdToTokenOwner[_tokenId] = _to;
tokenOwnerToTokenCount[_to]++;
}
emit Transfer(_from, _to, _tokenId);
}
function transferFrom(address _from, address _to, uint256 _tokenId) external {
_transferFrom(_from, _to, _tokenId);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external {
_transferFrom(_from, _to, _tokenId);
if (isContract(_to)) {
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, "");
require(retval == ERC721_RECEIVED_OLD);
}
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external {
_transferFrom(_from, _to, _tokenId);
if (isContract(_to)) {
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == ERC721_RECEIVED_OLD);
}
}
////////////////////////////////////////////////////////
// ERC998ERC721 and ERC998ERC721Enumerable implementation
////////////////////////////////////////////////////////
// tokenId => child contract
mapping(uint256 => address[]) internal childContracts;
// tokenId => (child address => contract index+1)
mapping(uint256 => mapping(address => uint256)) internal childContractIndex;
// tokenId => (child address => array of child tokens)
mapping(uint256 => mapping(address => uint256[])) internal childTokens;
// tokenId => (child address => (child token => child index+1)
mapping(uint256 => mapping(address => mapping(uint256 => uint256))) internal childTokenIndex;
// child address => childId => tokenId
mapping(address => mapping(uint256 => uint256)) internal childTokenOwner;
function _removeChild(uint256 _tokenId, address _childContract, uint256 _childTokenId) internal whenNotPaused {
uint256 tokenIndex = childTokenIndex[_tokenId][_childContract][_childTokenId];
require(tokenIndex != 0, "Child token not owned by token.");
// remove child token
uint256 lastTokenIndex = childTokens[_tokenId][_childContract].length - 1;
uint256 lastToken = childTokens[_tokenId][_childContract][lastTokenIndex];
// if (_childTokenId == lastToken) {
childTokens[_tokenId][_childContract][tokenIndex - 1] = lastToken;
childTokenIndex[_tokenId][_childContract][lastToken] = tokenIndex;
// }
childTokens[_tokenId][_childContract].length--;
delete childTokenIndex[_tokenId][_childContract][_childTokenId];
delete childTokenOwner[_childContract][_childTokenId];
// remove contract
if (lastTokenIndex == 0) {
uint256 lastContractIndex = childContracts[_tokenId].length - 1;
address lastContract = childContracts[_tokenId][lastContractIndex];
if (_childContract != lastContract) {
uint256 contractIndex = childContractIndex[_tokenId][_childContract];
childContracts[_tokenId][contractIndex] = lastContract;
childContractIndex[_tokenId][lastContract] = contractIndex;
}
childContracts[_tokenId].length--;
delete childContractIndex[_tokenId][_childContract];
}
}
function safeTransferChild(uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId) external {
_transferChild(_fromTokenId, _to, _childContract, _childTokenId);
ERC721(_childContract).safeTransferFrom(this, _to, _childTokenId);
}
function safeTransferChild(uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId, bytes _data) external {
_transferChild(_fromTokenId, _to, _childContract, _childTokenId);
ERC721(_childContract).safeTransferFrom(this, _to, _childTokenId, _data);
}
function transferChild(uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId) external {
_transferChild(_fromTokenId, _to, _childContract, _childTokenId);
//this is here to be compatible with cryptokitties and other old contracts that require being owner and approved
// before transferring.
//does not work with current standard which does not allow approving self, so we must let it fail in that case.
//0x095ea7b3 == "approve(address,uint256)"
bytes memory calldata = abi.encodeWithSelector(0x095ea7b3, this, _childTokenId);
assembly {
let success := call(gas, _childContract, 0, add(calldata, 0x20), mload(calldata), calldata, 0)
}
ERC721(_childContract).transferFrom(this, _to, _childTokenId);
}
function _transferChild(uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId) internal {
uint256 tokenId = childTokenOwner[_childContract][_childTokenId];
require(tokenId > 0 || childTokenIndex[tokenId][_childContract][_childTokenId] > 0);
require(tokenId == _fromTokenId);
require(_to != address(0));
address rootOwner = address(rootOwnerOf(tokenId));
require(rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][tokenId] == msg.sender);
_removeChild(tokenId, _childContract, _childTokenId);
emit TransferChild(_fromTokenId, _to, _childContract, _childTokenId);
}
function transferChildToParent(uint256 _fromTokenId, address _toContract, uint256 _toTokenId, address _childContract, uint256 _childTokenId, bytes _data) external {
uint256 tokenId = childTokenOwner[_childContract][_childTokenId];
require(tokenId > 0 || childTokenIndex[tokenId][_childContract][_childTokenId] > 0);
require(tokenId == _fromTokenId);
require(_toContract != address(0));
address rootOwner = address(rootOwnerOf(tokenId));
require(rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][tokenId] == msg.sender);
_removeChild(_fromTokenId, _childContract, _childTokenId);
ERC998ERC721BottomUp(_childContract).transferToParent(address(this), _toContract, _toTokenId, _childTokenId, _data);
emit TransferChild(_fromTokenId, _toContract, _childContract, _childTokenId);
}
// this contract has to be approved first in _childContract
function getChild(address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId) external {
_receiveChild(_from, _tokenId, _childContract, _childTokenId);
require(_from == msg.sender ||
ERC721(_childContract).isApprovedForAll(_from, msg.sender) ||
ERC721(_childContract).getApproved(_childTokenId) == msg.sender);
ERC721(_childContract).transferFrom(_from, this, _childTokenId);
}
function onERC721Received(address _from, uint256 _childTokenId, bytes _data) external returns (bytes4) {
require(_data.length > 0, "_data must contain the uint256 tokenId to transfer the child token to.");
// convert up to 32 bytes of_data to uint256, owner nft tokenId passed as uint in bytes
uint256 tokenId;
assembly {tokenId := calldataload(132)}
if (_data.length < 32) {
tokenId = tokenId >> 256 - _data.length * 8;
}
_receiveChild(_from, tokenId, msg.sender, _childTokenId);
require(ERC721(msg.sender).ownerOf(_childTokenId) != address(0), "Child token not owned.");
return ERC721_RECEIVED_OLD;
}
function onERC721Received(address _operator, address _from, uint256 _childTokenId, bytes _data) external returns (bytes4) {
require(_data.length > 0, "_data must contain the uint256 tokenId to transfer the child token to.");
// convert up to 32 bytes of_data to uint256, owner nft tokenId passed as uint in bytes
uint256 tokenId;
assembly {tokenId := calldataload(164)}
if (_data.length < 32) {
tokenId = tokenId >> 256 - _data.length * 8;
}
_receiveChild(_from, tokenId, msg.sender, _childTokenId);
require(ERC721(msg.sender).ownerOf(_childTokenId) != address(0), "Child token not owned.");
return ERC721_RECEIVED_NEW;
}
function _receiveChild(address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId) internal whenNotPaused {
require(tokenIdToTokenOwner[_tokenId] != address(0), "_tokenId does not exist.");
require(childTokenIndex[_tokenId][_childContract][_childTokenId] == 0, "Cannot receive child token because it has already been received.");
uint256 childTokensLength = childTokens[_tokenId][_childContract].length;
if (childTokensLength == 0) {
childContractIndex[_tokenId][_childContract] = childContracts[_tokenId].length;
childContracts[_tokenId].push(_childContract);
}
childTokens[_tokenId][_childContract].push(_childTokenId);
childTokenIndex[_tokenId][_childContract][_childTokenId] = childTokensLength + 1;
childTokenOwner[_childContract][_childTokenId] = _tokenId;
emit ReceivedChild(_from, _tokenId, _childContract, _childTokenId);
}
function _ownerOfChild(address _childContract, uint256 _childTokenId) internal view returns (address parentTokenOwner, uint256 parentTokenId) {
parentTokenId = childTokenOwner[_childContract][_childTokenId];
require(parentTokenId > 0 || childTokenIndex[parentTokenId][_childContract][_childTokenId] > 0);
return (tokenIdToTokenOwner[parentTokenId], parentTokenId);
}
function ownerOfChild(address _childContract, uint256 _childTokenId) external view returns (bytes32 parentTokenOwner, uint256 parentTokenId) {
parentTokenId = childTokenOwner[_childContract][_childTokenId];
require(parentTokenId > 0 || childTokenIndex[parentTokenId][_childContract][_childTokenId] > 0);
return (ERC998_MAGIC_VALUE << 224 | bytes32(tokenIdToTokenOwner[parentTokenId]), parentTokenId);
}
function childExists(address _childContract, uint256 _childTokenId) external view returns (bool) {
uint256 tokenId = childTokenOwner[_childContract][_childTokenId];
return childTokenIndex[tokenId][_childContract][_childTokenId] != 0;
}
function totalChildContracts(uint256 _tokenId) external view returns (uint256) {
return childContracts[_tokenId].length;
}
function childContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address childContract) {
require(_index < childContracts[_tokenId].length, "Contract address does not exist for this token and index.");
return childContracts[_tokenId][_index];
}
function totalChildTokens(uint256 _tokenId, address _childContract) external view returns (uint256) {
return childTokens[_tokenId][_childContract].length;
}
function childTokenByIndex(uint256 _tokenId, address _childContract, uint256 _index) external view returns (uint256 childTokenId) {
require(_index < childTokens[_tokenId][_childContract].length, "Token does not own a child token at contract address and index.");
return childTokens[_tokenId][_childContract][_index];
}
////////////////////////////////////////////////////////
// ERC998ERC223 and ERC998ERC223Enumerable implementation
////////////////////////////////////////////////////////
// tokenId => token contract
mapping(uint256 => address[]) erc20Contracts;
// tokenId => (token contract => token contract index)
mapping(uint256 => mapping(address => uint256)) erc20ContractIndex;
// tokenId => (token contract => balance)
mapping(uint256 => mapping(address => uint256)) erc20Balances;
function balanceOfERC20(uint256 _tokenId, address _erc20Contract) external view returns (uint256) {
return erc20Balances[_tokenId][_erc20Contract];
}
function removeERC20(uint256 _tokenId, address _erc20Contract, uint256 _value) private {
if (_value == 0) {
return;
}
uint256 erc20Balance = erc20Balances[_tokenId][_erc20Contract];
require(erc20Balance >= _value, "Not enough token available to transfer.");
uint256 newERC20Balance = erc20Balance - _value;
erc20Balances[_tokenId][_erc20Contract] = newERC20Balance;
if (newERC20Balance == 0) {
uint256 lastContractIndex = erc20Contracts[_tokenId].length - 1;
address lastContract = erc20Contracts[_tokenId][lastContractIndex];
if (_erc20Contract != lastContract) {
uint256 contractIndex = erc20ContractIndex[_tokenId][_erc20Contract];
erc20Contracts[_tokenId][contractIndex] = lastContract;
erc20ContractIndex[_tokenId][lastContract] = contractIndex;
}
erc20Contracts[_tokenId].length--;
delete erc20ContractIndex[_tokenId][_erc20Contract];
}
}
function transferERC20(uint256 _tokenId, address _to, address _erc20Contract, uint256 _value) external {
require(_to != address(0));
address rootOwner = address(rootOwnerOf(_tokenId));
require(rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] == msg.sender);
removeERC20(_tokenId, _erc20Contract, _value);
require(ERC20AndERC223(_erc20Contract).transfer(_to, _value), "ERC20 transfer failed.");
emit TransferERC20(_tokenId, _to, _erc20Contract, _value);
}
// implementation of ERC 223
function transferERC223(uint256 _tokenId, address _to, address _erc223Contract, uint256 _value, bytes _data) external {
require(_to != address(0));
address rootOwner = address(rootOwnerOf(_tokenId));
require(rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] == msg.sender);
removeERC20(_tokenId, _erc223Contract, _value);
require(ERC20AndERC223(_erc223Contract).transfer(_to, _value, _data), "ERC223 transfer failed.");
emit TransferERC20(_tokenId, _to, _erc223Contract, _value);
}
// this contract has to be approved first by _erc20Contract
function getERC20(address _from, uint256 _tokenId, address _erc20Contract, uint256 _value) public {
bool allowed = _from == msg.sender;
if (!allowed) {
uint256 remaining;
// 0xdd62ed3e == allowance(address,address)
bytes memory calldata = abi.encodeWithSelector(0xdd62ed3e, _from, msg.sender);
bool callSuccess;
assembly {
callSuccess := staticcall(gas, _erc20Contract, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
remaining := mload(calldata)
}
}
require(callSuccess, "call to allowance failed");
require(remaining >= _value, "Value greater than remaining");
allowed = true;
}
require(allowed, "not allowed to getERC20");
erc20Received(_from, _tokenId, _erc20Contract, _value);
require(ERC20AndERC223(_erc20Contract).transferFrom(_from, this, _value), "ERC20 transfer failed.");
}
function erc20Received(address _from, uint256 _tokenId, address _erc20Contract, uint256 _value) private {
require(tokenIdToTokenOwner[_tokenId] != address(0), "_tokenId does not exist.");
if (_value == 0) {
return;
}
uint256 erc20Balance = erc20Balances[_tokenId][_erc20Contract];
if (erc20Balance == 0) {
erc20ContractIndex[_tokenId][_erc20Contract] = erc20Contracts[_tokenId].length;
erc20Contracts[_tokenId].push(_erc20Contract);
}
erc20Balances[_tokenId][_erc20Contract] += _value;
emit ReceivedERC20(_from, _tokenId, _erc20Contract, _value);
}
// used by ERC 223
function tokenFallback(address _from, uint256 _value, bytes _data) external {
require(_data.length > 0, "_data must contain the uint256 tokenId to transfer the token to.");
require(isContract(msg.sender), "msg.sender is not a contract");
/**************************************
* TODO move to library
**************************************/
// convert up to 32 bytes of_data to uint256, owner nft tokenId passed as uint in bytes
uint256 tokenId;
assembly {
tokenId := calldataload(132)
}
if (_data.length < 32) {
tokenId = tokenId >> 256 - _data.length * 8;
}
//END TODO
erc20Received(_from, tokenId, msg.sender, _value);
}
function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address) {
require(_index < erc20Contracts[_tokenId].length, "Contract address does not exist for this token and index.");
return erc20Contracts[_tokenId][_index];
}
function totalERC20Contracts(uint256 _tokenId) external view returns (uint256) {
return erc20Contracts[_tokenId].length;
}
}
contract ERC998TopDownToken is SupportsInterfaceWithLookup, ERC721Enumerable, ERC721Metadata, ComposableTopDown {
using UrlStr for string;
using SafeMath for uint256;
string internal BASE_URL = "https://www.bitguild.com/bitizens/api/avatar/getAvatar/00000000";
bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
/**
* @dev Constructor function
*/
constructor() public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
_registerInterface(bytes4(ERC998_MAGIC_VALUE));
}
modifier existsToken(uint256 _tokenId){
address owner = tokenIdToTokenOwner[_tokenId];
require(owner != address(0), "This tokenId is invalid");
_;
}
function updateBaseURI(string _url) external onlyOwner {
BASE_URL = _url;
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string) {
return "Bitizen";
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string) {
return "BTZN";
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) external view existsToken(_tokenId) returns (string) {
return BASE_URL.generateUrl(_tokenId);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256)
{
require(address(0) != _owner);
require(_index < tokenOwnerToTokenCount[_owner]);
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenTo(address _to, uint256 _tokenId) internal whenNotPaused {
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFrom(address _from, uint256 _tokenId) internal whenNotPaused {
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal whenNotPaused {
super._mint(_to, _tokenId);
_addTokenTo(_to,_tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
//override
//add Enumerable info
function _transferFrom(address _from, address _to, uint256 _tokenId) internal whenNotPaused {
// not allown to transfer when only one avatar
super._transferFrom(_from, _to, _tokenId);
_addTokenTo(_to,_tokenId);
_removeTokenFrom(_from, _tokenId);
}
}
interface AvatarChildService {
/**
@dev if you want your contract become a avatar child, please let your contract inherit this interface
@param _tokenId1 first child token id
@param _tokenId2 second child token id
@return true will unmount first token before mount ,false will directly mount child
*/
function compareItemSlots(uint256 _tokenId1, uint256 _tokenId2) external view returns (bool _res);
/**
@dev if you want your contract become a avatar child, please let your contract inherit this interface
@return return true will be to avatar child
*/
function isAvatarChild(uint256 _tokenId) external view returns(bool);
}
interface AvatarService {
function updateAvatarInfo(address _owner, uint256 _tokenId, string _name, uint256 _dna) external;
function createAvatar(address _owner, string _name, uint256 _dna) external returns(uint256);
function getMountedChildren(address _owner,uint256 _tokenId, address _childAddress) external view returns(uint256[]);
function getAvatarInfo(uint256 _tokenId) external view returns (string _name, uint256 _dna);
function getOwnedAvatars(address _owner) external view returns(uint256[] _avatars);
function unmount(address _owner, address _childContract, uint256[] _children, uint256 _avatarId) external;
function mount(address _owner, address _childContract, uint256[] _children, uint256 _avatarId) external;
}
contract AvatarToken is ERC998TopDownToken, AvatarService {
using UrlStr for string;
enum ChildHandleType{NULL, MOUNT, UNMOUNT}
event ChildHandle(address indexed from, uint256 parent, address indexed childAddr, uint256[] children, ChildHandleType _type);
event AvatarTransferStateChanged(address indexed _owner, bool _newState);
struct Avatar {
// avatar name
string name;
// avatar gen,this decide avatar appearance
uint256 dna;
}
// avatar id index
uint256 internal avatarIndex = 0;
// avatar id => avatar
mapping(uint256 => Avatar) avatars;
// true avatar can do transfer
bool public avatarTransferState = false;
function changeAvatarTransferState(bool _newState) public onlyOwner {
if(avatarTransferState == _newState) return;
avatarTransferState = _newState;
emit AvatarTransferStateChanged(owner, avatarTransferState);
}
function createAvatar(address _owner, string _name, uint256 _dna) external onlyOperator returns(uint256) {
return _createAvatar(_owner, _name, _dna);
}
function getMountedChildren(address _owner, uint256 _avatarId, address _childAddress)
external
view
onlyOperator
existsToken(_avatarId)
returns(uint256[]) {
require(_childAddress != address(0));
require(tokenIdToTokenOwner[_avatarId] == _owner);
return childTokens[_avatarId][_childAddress];
}
function updateAvatarInfo(address _owner, uint256 _avatarId, string _name, uint256 _dna) external onlyOperator existsToken(_avatarId){
require(_owner != address(0), "Invalid address");
require(_owner == tokenIdToTokenOwner[_avatarId] || msg.sender == owner);
Avatar storage avatar = avatars[_avatarId];
avatar.name = _name;
avatar.dna = _dna;
}
function getOwnedAvatars(address _owner) external view onlyOperator returns(uint256[] _avatars) {
require(_owner != address(0));
_avatars = ownedTokens[_owner];
}
function getAvatarInfo(uint256 _avatarId) external view existsToken(_avatarId) returns(string _name, uint256 _dna) {
Avatar storage avatar = avatars[_avatarId];
_name = avatar.name;
_dna = avatar.dna;
}
function unmount(address _owner, address _childContract, uint256[] _children, uint256 _avatarId) external onlyOperator {
if(_children.length == 0) return;
require(ownerOf(_avatarId) == _owner); // check avatar owner
uint256[] memory mountedChildren = childTokens[_avatarId][_childContract];
if (mountedChildren.length == 0) return;
uint256[] memory unmountChildren = new uint256[](_children.length); // record unmount children
for(uint8 i = 0; i < _children.length; i++) {
uint256 child = _children[i];
if(_isMounted(mountedChildren, child)){
unmountChildren[i] = child;
_removeChild(_avatarId, _childContract, child);
ERC721(_childContract).transferFrom(this, _owner, child);
}
}
if(unmountChildren.length > 0 )
emit ChildHandle(_owner, _avatarId, _childContract, unmountChildren, ChildHandleType.UNMOUNT);
}
function mount(address _owner, address _childContract, uint256[] _children, uint256 _avatarId) external onlyOperator {
if(_children.length == 0) return;
require(ownerOf(_avatarId) == _owner); // check avatar owner
for(uint8 i = 0; i < _children.length; i++) {
uint256 child = _children[i];
require(ERC721(_childContract).ownerOf(child) == _owner); // check child owner
_receiveChild(_owner, _avatarId, _childContract, child);
ERC721(_childContract).transferFrom(_owner, this, child);
}
emit ChildHandle(_owner, _avatarId, _childContract, _children, ChildHandleType.MOUNT);
}
// check every have mounted children with the will mount child relationship
function _checkChildRule(address _owner, uint256 _avatarId, address _childContract, uint256 _child) internal {
uint256[] memory tokens = childTokens[_avatarId][_childContract];
if (tokens.length == 0) {
if (!AvatarChildService(_childContract).isAvatarChild(_child)) {
revert("it can't be avatar child");
}
}
for (uint256 i = 0; i < tokens.length; i++) {
if (AvatarChildService(_childContract).compareItemSlots(tokens[i], _child)) {
_removeChild(_avatarId, _childContract, tokens[i]);
ERC721(_childContract).transferFrom(this, _owner, tokens[i]);
}
}
}
/// false will ignore not mounted children on this avatar and not exist children
function _isMounted(uint256[] mountedChildren, uint256 _toMountToken) private pure returns (bool) {
for(uint8 i = 0; i < mountedChildren.length; i++) {
if(mountedChildren[i] == _toMountToken){
return true;
}
}
return false;
}
// create avatar
function _createAvatar(address _owner, string _name, uint256 _dna) private returns(uint256 _avatarId) {
require(_owner != address(0));
Avatar memory avatar = Avatar(_name, _dna);
_avatarId = ++avatarIndex;
avatars[_avatarId] = avatar;
_mint(_owner, _avatarId);
}
// override
function _transferFrom(address _from, address _to, uint256 _avatarId) internal whenNotPaused {
// add transfer control
require(avatarTransferState == true, "current time not allown transfer avatar");
super._transferFrom(_from, _to, _avatarId);
}
// override
function _receiveChild(address _from, uint256 _avatarId, address _childContract, uint256 _childTokenId) internal whenNotPaused {
_checkChildRule(_from, _avatarId, _childContract, _childTokenId);
super._receiveChild(_from, _avatarId, _childContract, _childTokenId);
}
function () public payable {
revert();
}
}
|
getChild function enables older contracts like cryptokitties to be transferred into a composable The _childContract must approve this contract. Then getChild can be called.
|
interface ERC998ERC721TopDown {
event ReceivedChild(address indexed _from, uint256 indexed _tokenId, address indexed _childContract, uint256 _childTokenId);
event TransferChild(uint256 indexed tokenId, address indexed _to, address indexed _childContract, uint256 _childTokenId);
function rootOwnerOf(uint256 _tokenId) external view returns (bytes32 rootOwner);
function rootOwnerOfChild(address _childContract, uint256 _childTokenId) external view returns (bytes32 rootOwner);
function ownerOfChild(address _childContract, uint256 _childTokenId) external view returns (bytes32 parentTokenOwner, uint256 parentTokenId);
function onERC721Received(address _operator, address _from, uint256 _childTokenId, bytes _data) external returns (bytes4);
function transferChild(uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId) external;
function safeTransferChild(uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId) external;
function safeTransferChild(uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId, bytes _data) external;
function transferChildToParent(uint256 _fromTokenId, address _toContract, uint256 _toTokenId, address _childContract, uint256 _childTokenId, bytes _data) external;
function getChild(address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId) external;
}
| 945,986 |
./full_match/1/0xd9dF2211b576D430FAb3BD93f915a1345974D797/sources/contracts/v1/interfaces/IERC721MultiCollection.sol
|
ERC721Multi collection interface Particle Collection - valdi.eth Adds public facing and multi collection balanceOf and collectionId to tokenId functions This implements an optional extension of {ERC721} that adds support for multiple collections and enumerability of all the token ids in the contract as well as all token ids owned by each account per collection. Determine if a collection exists.
|
interface IERC721MultiCollection is IERC721 {
event CollectionAdded(uint256 indexed collectionId);
event NewCollectionsForbidden();
function collectionExists(uint256 collectionId) external view returns (bool);
function balanceOf(address owner, uint256 collectionId) external view returns (uint256);
function tokenIdToCollectionId(uint256 tokenId) external view returns (uint256 collectionId);
function numberOfCollections() external view returns (uint256);
function tokenTotalSupply(uint256 collectionId) external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index, uint256 collectionId) external view returns (uint256);
function MAX_COLLECTION_SIZE() external view returns (uint256);
pragma solidity 0.8.17;
}
| 8,408,823 |
./full_match/1/0x877C7ae9D03A4b0daA55eC74Eb6409853b1cfbA1/sources/browser/TorroCollab.sol
|
Spending allowance. owner_ token owner address. spender_ token spender address. return uint256 amount of owner's tokens that spender can use.
|
function allowance(address owner_, address spender_) public view returns (uint256) {
return 0;
}
| 3,154,280 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../InterestModel/BaseJumpRateModelV2.sol";
import "../InterestModel/InterestRateModel.sol";
import "../Utils/SafeMath.sol";
/**
* @title Compound's JumpRateModel Contract V2 for V2 cTokens
* @author Arr00
* @notice Supports only for V2 cTokens
*/
contract JumpRateModelV2 is InterestRateModel, BaseJumpRateModelV2 {
using SafeMath for uint;
/**
* @notice Calculates the current borrow rate per block
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market
* @return The borrow rate percentage per block as a mantissa (scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view override returns (uint) {
return super.getBorrowRateInternal(cash, borrows, reserves);
}
/**
* @notice Calculates the current supply rate per block
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market
* @param reserveFactorMantissa The current reserve factor for the market
* @return The supply rate percentage per block as a mantissa (scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) public view override(InterestRateModel, BaseJumpRateModelV2) returns (uint) {
uint oneMinusReserveFactor = uint(1e18).sub(reserveFactorMantissa);
uint borrowRate = getBorrowRateInternal(cash, borrows, reserves);
uint rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18);
return utilizationRate(cash, borrows, reserves).mul(rateToPool).div(1e18);
}
constructor(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_, address owner_)
BaseJumpRateModelV2(baseRatePerYear,multiplierPerYear,jumpMultiplierPerYear,kink_,owner_) {}
}
|
Calculates the current supply rate per block cash The amount of cash in the market borrows The amount of borrows in the market reserves The amount of reserves in the market reserveFactorMantissa The current reserve factor for the market return The supply rate percentage per block as a mantissa (scaled by 1e18)/
|
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) public view override(InterestRateModel, BaseJumpRateModelV2) returns (uint) {
uint oneMinusReserveFactor = uint(1e18).sub(reserveFactorMantissa);
uint borrowRate = getBorrowRateInternal(cash, borrows, reserves);
uint rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18);
return utilizationRate(cash, borrows, reserves).mul(rateToPool).div(1e18);
}
constructor(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_, address owner_)
| 12,837,378 |
// UstxDex.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.0;
import "./ERC20.sol";
import "./ERC20Detailed.sol";
import "./UpStableToken.sol";
import "./IERC20.sol";
import "./ReentrancyGuard.sol";
import "./Pausable.sol";
import "./AdminRole.sol";
import "./SafeMath.sol";
/// @title Up Stable Token eXperiment DEX
/// @author USTX Team
/// @dev This contract implements the DEX functionality for the USTX token.
contract UstxDEX is ReentrancyGuard,Pausable {
/***********************************|
| Variables && Events |
|__________________________________*/
//Constants
uint256 private constant MAX_FEE = 200; //maximum fee in BP (2.5%)
uint256 private constant MAX_LAUNCH_FEE = 1000; //maximum fee during launchpad (10%)
//Variables
uint256 private _decimals; // 6
uint256 private _feeBuy; //buy fee in basis points
uint256 private _feeSell; //sell fee in basis points
uint256 private _targetRatioExp; //target reserve ratio for expansion in TH (1000s) to circulating cap
uint256 private _targetRatioDamp; //target reserve ratio for damping in TH (1000s) to circulating cap
uint256 private _expFactor; //expansion factor in TH
uint256 private _dampFactor; //damping factor in TH
uint256 private _minExp; //minimum expansion in TH
uint256 private _maxDamp; //maximum damping in TH
uint256 private _collectedFees; //amount of collected fees
uint256 private _launchEnabled; //launchpad mode if >=1
uint256 private _launchTargetSize; //number of tokens reserved for launchpad
uint256 private _launchPrice; //Launchpad price
uint256 private _launchBought; //number of tokens bought so far in Launchpad
uint256 private _launchMaxLot; //max number of usdtSold for a single operation during Launchpad
uint256 private _launchFee; //Launchpad fee
address private _launchTeamAddr; //Launchpad team address
UpStableToken Token; // address of the TRC20 token traded on this contract
IERC20 Tusdt; // address of the reserve token USDT
//SafeERC20 not needed for USDT(TRC20) and USTX(TRC20)
using SafeMath for uint256;
// Events
event TokenBuy(address indexed buyer, uint256 indexed usdtSold, uint256 indexed tokensBought, uint256 price);
event TokenSell(address indexed buyer, uint256 indexed tokensSold, uint256 indexed usdtBought, uint256 price);
event Snapshot(address indexed operator, uint256 indexed usdtBalance, uint256 indexed tokenBalance);
/**
* @dev Constructor
* @param tradeTokenAddr contract address of the traded token (USTX)
* @param reserveTokenAddr contract address of the reserve token (USDT)
*/
constructor (address tradeTokenAddr, address reserveTokenAddr)
AdminRole(2) //at least two administrsators always in charge
public {
require(tradeTokenAddr != address(0) && reserveTokenAddr != address(0), "Invalid contract address");
Token = UpStableToken(tradeTokenAddr);
Tusdt = IERC20(reserveTokenAddr);
_launchTeamAddr = _msgSender();
_decimals = 6;
_feeBuy = 0; //0%
_feeSell = 100; //1%
_targetRatioExp = 240; //24%
_targetRatioDamp = 260; //26%
_expFactor = 1000; //1
_dampFactor = 1000; //1
_minExp = 100; //0.1
_maxDamp = 100; //0.1
_collectedFees = 0;
_launchEnabled = 0;
}
/***********************************|
| Exchange Functions |
|__________________________________*/
/**
* @dev Public function to preview token purchase with exact input in USDT
* @param usdtSold amount of USDT to sell
* @return number of tokens that can be purchased with input usdtSold
*/
function buyTokenInputPreview(uint256 usdtSold) public view returns (uint256) {
require(usdtSold > 0, "USDT sold must greater than 0");
uint256 tokenReserve = Token.balanceOf(address(this));
uint256 usdtReserve = Tusdt.balanceOf(address(this));
(uint256 tokensBought,,) = _getBoughtMinted(usdtSold,tokenReserve,usdtReserve);
return tokensBought;
}
/**
* @dev Public function to preview token sale with exact input in tokens
* @param tokensSold amount of token to sell
* @return Amount of USDT that can be bought with input Tokens.
*/
function sellTokenInputPreview(uint256 tokensSold) public view returns (uint256) {
require(tokensSold > 0, "Tokens sold must greater than 0");
uint256 tokenReserve = Token.balanceOf(address(this));
uint256 usdtReserve = Tusdt.balanceOf(address(this));
(uint256 usdtsBought,,) = _getBoughtBurned(tokensSold,tokenReserve,usdtReserve);
return usdtsBought;
}
/**
* @dev Public function to buy tokens during launchpad
* @param rSell amount of UDST to sell
* @param minTokens minimum amount of tokens to buy
* @return number of tokens bought
*/
function buyTokenLaunchInput(uint256 rSell, uint256 minTokens) public whenNotPaused returns (uint256) {
require(_launchEnabled>0,"Function allowed only during launchpad");
require(_launchBought<_launchTargetSize,"Launchpad target reached!");
require(rSell<=_launchMaxLot,"Order too big for Launchpad");
return _buyLaunchpadInput(rSell, minTokens, _msgSender(), _msgSender());
}
/**
* @dev Public function to buy tokens during launchpad and transfer them to recipient
* @param rSell amount of UDST to sell
* @param minTokens minimum amount of tokens to buy
* @param recipient recipient of the transaction
* @return number of tokens bought
*/
function buyTokenLaunchTransferInput(uint256 rSell, uint256 minTokens, address recipient) public whenNotPaused returns(uint256) {
require(_launchEnabled>0,"Function allowed only during launchpad");
require(recipient != address(this) && recipient != address(0),"Recipient cannot be DEX or address 0");
require(_launchBought<_launchTargetSize,"Launchpad target reached!");
require(rSell<=_launchMaxLot,"Order too big for Launchpad");
return _buyLaunchpadInput(rSell, minTokens, _msgSender(), recipient);
}
/**
* @dev Public function to buy tokens
* @param rSell amount of UDST to sell
* @param minTokens minimum amount of tokens to buy
* @return number of tokens bought
*/
function buyTokenInput(uint256 rSell, uint256 minTokens) public whenNotPaused returns (uint256) {
require(_launchEnabled==0,"Function not allowed during launchpad");
return _buyStableInput(rSell, minTokens, _msgSender(), _msgSender());
}
/**
* @dev Public function to buy tokens and transfer them to recipient
* @param rSell amount of UDST to sell
* @param minTokens minimum amount of tokens to buy
* @param recipient recipient of the transaction
* @return number of tokens bought
*/
function buyTokenTransferInput(uint256 rSell, uint256 minTokens, address recipient) public whenNotPaused returns(uint256) {
require(_launchEnabled==0,"Function not allowed during launchpad");
require(recipient != address(this) && recipient != address(0),"Recipient cannot be DEX or address 0");
return _buyStableInput(rSell, minTokens, _msgSender(), recipient);
}
/**
* @dev Public function to sell tokens
* @param tokensSold number of tokens to sell
* @param minUsdts minimum number of UDST to buy
* @return number of USDTs bought
*/
function sellTokenInput(uint256 tokensSold, uint256 minUsdts) public whenNotPaused returns (uint256) {
require(_launchEnabled==0,"Function not allowed during launchpad");
return _sellStableInput(tokensSold, minUsdts, _msgSender(), _msgSender());
}
/**
* @dev Public function to sell tokens and trasnfer USDT to recipient
* @param tokensSold number of tokens to sell
* @param minUsdts minimum number of UDST to buy
* @param recipient recipient of the transaction
* @return number of USDTs bought
*/
function sellTokenTransferInput(uint256 tokensSold, uint256 minUsdts, address recipient) public whenNotPaused returns (uint256) {
require(_launchEnabled==0,"Function not allowed during launchpad");
require(recipient != address(this) && recipient != address(0),"Recipient cannot be DEX or address 0");
return _sellStableInput(tokensSold, minUsdts, _msgSender(), recipient);
}
/**
* @dev public function to setup the reserve after launchpad
* @param startPrice target price
* @return reserve value
*/
function setupReserve(uint256 startPrice) public onlyAdmin whenPaused returns (uint256) {
require(startPrice>0,"Price cannot be 0");
uint256 tokenReserve = Token.balanceOf(address(this));
uint256 usdtReserve = Tusdt.balanceOf(address(this));
uint256 newReserve = usdtReserve.mul(10**_decimals).div(startPrice);
uint256 temp;
if (newReserve>tokenReserve) {
temp = newReserve.sub(tokenReserve);
Token.mint(address(this),temp);
} else {
temp = tokenReserve.sub(newReserve);
Token.burn(temp);
}
return newReserve;
}
/**
* @dev Private function to buy tokens with exact input in USDT
*
*/
function _buyStableInput(uint256 usdtSold, uint256 minTokens, address buyer, address recipient) private nonReentrant returns (uint256) {
require(usdtSold > 0 && minTokens > 0,"USDT sold and min tokens should be higher than 0");
uint256 tokenReserve = Token.balanceOf(address(this));
uint256 usdtReserve = Tusdt.balanceOf(address(this));
(uint256 tokensBought, uint256 minted, uint256 fee) = _getBoughtMinted(usdtSold,tokenReserve,usdtReserve);
_collectedFees = _collectedFees.add(fee);
require(tokensBought >= minTokens, "Tokens bought lower than requested minimum amount");
if (minted>0) {
Token.mint(address(this),minted);
}
Tusdt.transferFrom(buyer, address(this), usdtSold);
if (fee>0) {
Tusdt.transfer(_launchTeamAddr,fee); //transfer fees to team
}
Token.transfer(address(recipient),tokensBought);
tokenReserve = Token.balanceOf(address(this)); //update token reserve
usdtReserve = Tusdt.balanceOf(address(this)); //update usdt reserve
uint256 newPrice = usdtReserve.mul(10**_decimals).div(tokenReserve); //calc new price
emit TokenBuy(buyer, usdtSold, tokensBought, newPrice); //emit TokenBuy event
emit Snapshot(buyer, usdtReserve, tokenReserve); //emit Snapshot event
return tokensBought;
}
/**
* @dev Private function to buy tokens during launchpad with exact input in USDT
*
*/
function _buyLaunchpadInput(uint256 usdtSold, uint256 minTokens, address buyer, address recipient) private nonReentrant returns (uint256) {
require(usdtSold > 0 && minTokens > 0, "USDT sold and min tokens should be higher than 0");
uint256 tokensBought = usdtSold.mul(10**_decimals).div(_launchPrice);
uint256 fee = usdtSold.mul(_launchFee).div(10000);
require(tokensBought >= minTokens, "Tokens bought lower than requested minimum amount");
_launchBought = _launchBought.add(tokensBought);
Token.mint(address(this),tokensBought); //mint new tokens
Tusdt.transferFrom(buyer, address(this), usdtSold); //add usdtSold to reserve
Tusdt.transfer(_launchTeamAddr,fee); //transfer fees to team
Token.transfer(address(recipient),tokensBought); //transfer tokens to recipient
emit TokenBuy(buyer, usdtSold, tokensBought, _launchPrice);
emit Snapshot(buyer, Tusdt.balanceOf(address(this)), Token.balanceOf(address(this)));
return tokensBought;
}
/**
* @dev Private function to sell tokens with exact input in tokens
*
*/
function _sellStableInput(uint256 tokensSold, uint256 minUsdts, address buyer, address recipient) private nonReentrant returns (uint256) {
require(tokensSold > 0 && minUsdts > 0, "Tokens sold and min USDT should be higher than 0");
uint256 tokenReserve = Token.balanceOf(address(this));
uint256 usdtReserve = Tusdt.balanceOf(address(this));
(uint256 usdtsBought, uint256 burned, uint256 fee) = _getBoughtBurned(tokensSold,tokenReserve,usdtReserve);
_collectedFees = _collectedFees.add(fee);
require(usdtsBought >= minUsdts, "USDT bought lower than requested minimum amount");
if (burned>0) {
Token.burn(burned);
}
Token.transferFrom(buyer, address(this), tokensSold); //transfer tokens to DEX
Tusdt.transfer(recipient,usdtsBought); //transfer USDT to user
if (fee>0) {
Tusdt.transfer(_launchTeamAddr,fee); //transfer fees to team
}
tokenReserve = Token.balanceOf(address(this)); //update token reserve
usdtReserve = Tusdt.balanceOf(address(this)); //update usdt reserve
uint256 newPrice = usdtReserve.mul(10**_decimals).div(tokenReserve); //calc new price
emit TokenSell(buyer, tokensSold, usdtsBought, newPrice); //emit Token event
emit Snapshot(buyer, usdtReserve, tokenReserve); //emit Snapshot event
return usdtsBought;
}
/**
* @dev Private function to get expansion correction
*
*/
function _getExp(uint256 tokenReserve, uint256 usdtReserve) private view returns (uint256,uint256) {
uint256 tokenCirc = Token.totalSupply(); //total
tokenCirc = tokenCirc.sub(tokenReserve);
uint256 price = getPrice(); //multiplied by 10**decimals
uint256 cirCap = price.mul(tokenCirc); //multiplied by 10**decimals
uint256 ratio = usdtReserve.mul(1000000000).div(cirCap);
uint256 exp = ratio.mul(1000).div(_targetRatioExp);
if (exp<1000) {
exp=1000;
}
exp = exp.sub(1000);
exp=exp.mul(_expFactor).div(1000);
if (exp<_minExp) {
exp=_minExp;
}
if (exp>1000) {
exp = 1000;
}
return (exp,ratio);
}
/**
* @dev Private function to get k exponential factor for expansion
*
*/
function _getKXe(uint256 pool, uint256 trade, uint256 exp) private pure returns (uint256) {
uint256 temp = 1000-exp;
temp = trade.mul(temp);
temp = temp.div(1000);
temp = temp.add(pool);
temp = temp.mul(1000000000);
uint256 kexp = temp.div(pool);
return kexp;
}
/**
* @dev Private function to get k exponential factor for damping
*
*/
function _getKXd(uint256 pool, uint256 trade, uint256 exp) private pure returns (uint256) {
uint256 temp = 1000-exp;
temp = trade.mul(temp);
temp = temp.div(1000);
temp = temp.add(pool);
uint256 kexp = pool.mul(1000000000).div(temp);
return kexp;
}
/**
* @dev Private function to get amount of tokens bought and minted
*
*/
function _getBoughtMinted(uint256 usdtSold, uint256 tokenReserve, uint256 usdtReserve) private view returns (uint256,uint256,uint256) {
uint256 fees = usdtSold.mul(_feeBuy).div(10000);
uint256 usdtSoldNet = usdtSold.sub(fees);
(uint256 exp,) = _getExp(tokenReserve,usdtReserve);
uint256 kexp = _getKXe(usdtReserve,usdtSoldNet,exp);
uint256 temp = tokenReserve.mul(usdtReserve); //k
temp = temp.mul(kexp);
temp = temp.mul(kexp);
uint256 kn = temp.div(1000000000000000000); //uint256 kn=tokenReserve.mul(usdtReserve).mul(kexp).mul(kexp).div(1000000);
temp = tokenReserve.mul(usdtReserve); //k
usdtReserve = usdtReserve.add(usdtSoldNet); //uint256 usdtReserveNew= usdtReserve.add(usdtSoldNet);
temp = temp.div(usdtReserve); //USTXamm
uint256 tokensBought = tokenReserve.sub(temp); //out=tokenReserve-USTXamm
temp=kn.div(usdtReserve); //USXTPool_n
uint256 minted=temp.add(tokensBought).sub(tokenReserve);
return (tokensBought, minted, fees);
}
/**
* @dev Private function to get damping correction
*
*/
function _getDamp(uint256 tokenReserve, uint256 usdtReserve) private view returns (uint256,uint256) {
uint256 tokenCirc = Token.totalSupply(); //total
tokenCirc = tokenCirc.sub(tokenReserve);
uint256 price = getPrice(); //multiplied by 10**decimals
uint256 cirCap = price.mul(tokenCirc); //multiplied by 10**decimals
uint256 ratio = usdtReserve.mul(1000000000).div(cirCap); //in TH
if (ratio>_targetRatioDamp) {
ratio=_targetRatioDamp;
}
uint256 damp = _targetRatioDamp.sub(ratio);
damp = damp.mul(_dampFactor).div(_targetRatioDamp);
if (damp<_maxDamp) {
damp=_maxDamp;
}
if (damp>1000) {
damp = 1000;
}
return (damp,ratio);
}
/**
* @dev Private function to get number of USDT bought and tokens burned
*
*/
function _getBoughtBurned(uint256 tokenSold, uint256 tokenReserve, uint256 usdtReserve) private view returns (uint256,uint256,uint256) {
(uint256 damp,) = _getDamp(tokenReserve,usdtReserve);
uint256 kexp = _getKXd(tokenReserve,tokenSold,damp);
uint256 k = tokenReserve.mul(usdtReserve); //k
uint256 temp = k.mul(kexp);
temp = temp.mul(kexp);
uint256 kn = temp.div(1000000000000000000); //uint256 kn=tokenReserve.mul(usdtReserve).mul(kexp).mul(kexp).div(1000000);
tokenReserve = tokenReserve.add(tokenSold); //USTXpool_n
temp = k.div(tokenReserve); //USDamm
uint256 usdtsBought = usdtReserve.sub(temp); //out
usdtReserve = temp;
temp = kn.div(usdtReserve); //USTXPool_n
uint256 burned=tokenReserve.sub(temp);
temp = usdtsBought.mul(_feeSell).div(10000); //fee
usdtsBought = usdtsBought.sub(temp);
return (usdtsBought, burned, temp);
}
/**************************************|
| Getter and Setter Functions |
|_____________________________________*/
/**
* @dev Function to set Token address (only admin)
* @param tokenAddress address of the traded token contract
*/
function setTokenAddr(address tokenAddress) public onlyAdmin {
require(tokenAddress != address(0), "INVALID_ADDRESS");
Token = UpStableToken(tokenAddress);
}
/**
* @dev Function to set USDT address (only admin)
* @param reserveAddress address of the reserve token contract
*/
function setReserveTokenAddr(address reserveAddress) public onlyAdmin {
require(reserveAddress != address(0), "INVALID_ADDRESS");
Tusdt = IERC20(reserveAddress);
}
/**
* @dev Function to set fees (only admin)
* @param feeBuy fee for buy operations (in basis points)
* @param feeSell fee for sell operations (in basis points)
*/
function setFees(uint256 feeBuy, uint256 feeSell) public onlyAdmin {
require(feeBuy<=MAX_FEE && feeSell<=MAX_FEE,"Fees cannot be higher than MAX_FEE");
_feeBuy=feeBuy;
_feeSell=feeSell;
}
/**
* @dev Function to get fees
* @return buy and sell fees in basis points
*
*/
function getFees() public view returns (uint256, uint256) {
return (_feeBuy, _feeSell);
}
/**
* @dev Function to set target ratio level (only admin)
* @param ratioExp target reserve ratio for expansion (in thousandths)
* @param ratioDamp target reserve ratio for damping (in thousandths)
*/
function setTargetRatio(uint256 ratioExp, uint256 ratioDamp) public onlyAdmin {
require(ratioExp<=1000 && ratioExp>=10 && ratioDamp<=1000 && ratioDamp >=10,"Target ratio must be between 1% and 100%");
_targetRatioExp = ratioExp; //in TH
_targetRatioDamp = ratioDamp; //in TH
}
/**
* @dev Function to get target ratio level
* return ratioExp and ratioDamp in thousandths
*
*/
function getTargetRatio() public view returns (uint256, uint256) {
return (_targetRatioExp, _targetRatioDamp);
}
/**
* @dev Function to get currect reserve ratio level
* return current ratio in thousandths
*
*/
function getCurrentRatio() public view returns (uint256) {
uint256 tokenReserve = Token.balanceOf(address(this));
uint256 usdtReserve = Tusdt.balanceOf(address(this));
uint256 tokenCirc = Token.totalSupply(); //total
tokenCirc = tokenCirc.sub(tokenReserve);
uint256 price = getPrice(); //multiplied by 10**decimals
uint256 cirCap = price.mul(tokenCirc); //multiplied by 10**decimals
uint256 ratio = usdtReserve.mul(1000000000).div(cirCap); //in TH
return ratio;
}
/**
* @dev Function to set target expansion factors (only admin)
* @param expF expansion factor (in thousandths)
* @param minExp minimum expansion coefficient to use (in thousandths)
*/
function setExpFactors(uint256 expF, uint256 minExp) public onlyAdmin {
require(expF<=10000 && minExp<=1000,"Expansion factor cannot be more than 1000% and the minimum expansion cannot be over 100%");
_expFactor=expF;
_minExp=minExp;
}
/**
* @dev Function to get expansion factors
* @return _expFactor and _minExp in thousandths
*
*/
function getExpFactors() public view returns (uint256, uint256) {
return (_expFactor,_minExp);
}
/**
* @dev Function to set target damping factors (only admin)
* @param dampF damping factor (in thousandths)
* @param maxDamp maximum damping to use (in thousandths)
*/
function setDampFactors(uint256 dampF, uint256 maxDamp) public onlyAdmin {
require(dampF<=1000 && maxDamp<=1000,"Damping factor cannot be more than 100% and the maximum damping be over 100%");
_dampFactor=dampF;
_maxDamp=maxDamp;
}
/**
* @dev Function to get damping factors
* @return _dampFactor and _maxDamp in thousandths
*
*/
function getDampFactors() public view returns (uint256, uint256) {
return (_dampFactor,_maxDamp);
}
/**
* @dev Function to get current price
* @return current price
*
*/
function getPrice() public view returns (uint256) {
if (_launchEnabled>0) {
return (_launchPrice);
}else {
uint256 tokenReserve = Token.balanceOf(address(this));
uint256 usdtReserve = Tusdt.balanceOf(address(this));
return (usdtReserve.mul(10**_decimals).div(tokenReserve)); //price with decimals
}
}
/**
* @dev Function to get address of the traded token contract
* @return Address of token that is traded on this exchange
*
*/
function getTokenAddress() public view returns (address) {
return address(Token);
}
/**
* @dev Function to get the address of the reserve token contract
* @return Address of USDT
*
*/
function getReserveAddress() public view returns (address) {
return address(Tusdt);
}
/**
* @dev Function to get current reserves balance
* @return USDT reserve, USTX reserve, USTX circulating
*/
function getBalances() public view returns (uint256,uint256,uint256,uint256) {
uint256 tokenReserve = Token.balanceOf(address(this));
uint256 usdtReserve = Tusdt.balanceOf(address(this));
uint256 tokenCirc = Token.totalSupply().sub(tokenReserve);
return (usdtReserve,tokenReserve,tokenCirc,_collectedFees);
}
/**
* @dev Function to enable launchpad (only admin)
* @param price launchpad fixed price
* @param target launchpad target USTX sale
* @param maxLot launchpad maximum purchase size in USDT
* @param fee launchpad fee for the dev team (in basis points)
* @return true if launchpad is enabled
*/
function enableLaunchpad(uint256 price, uint256 target, uint256 maxLot, uint256 fee) public onlyAdmin returns (bool) {
require(price>0 && target>0 && maxLot>0 && fee<=MAX_LAUNCH_FEE,"Price, target and max lotsize cannot be 0. Fee must be lower than MAX_LAUNCH_FEE");
_launchPrice = price; //in USDT units
_launchTargetSize = target; //in USTX units
_launchBought = 0; //in USTX units
_launchFee = fee; //in bp
_launchMaxLot = maxLot; //in USDT units
_launchEnabled = 1;
return true;
}
/**
* @dev Function to disable launchpad (only admin)
*
*
*/
function disableLaunchpad() public onlyAdmin {
_launchEnabled = 0;
}
/**
* @dev Function to get launchpad status (only admin)
* @return enabled state, price, amount of tokens bought, target tokens, max ourschase lot, fee
*
*/
function getLaunchpadStatus() public view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
return (_launchEnabled,_launchPrice,_launchBought,_launchTargetSize,_launchMaxLot,_launchFee);
}
/**
* @dev Set team address (only admin)
* @param team address for collecting fees
*/
function setTeamAddress(address team) public onlyAdmin {
require(team != address(0) && team != address(this), "Invalid team address");
_launchTeamAddr = team;
}
/**
* @dev Unregister DEX as admin from USTX contract
*
*/
function unregisterAdmin() public onlyAdmin {
Token.renounceAdmin();
}
}
|
public function to setup the reserve after launchpad startPrice target price return reserve value/
|
function setupReserve(uint256 startPrice) public onlyAdmin whenPaused returns (uint256) {
require(startPrice>0,"Price cannot be 0");
uint256 tokenReserve = Token.balanceOf(address(this));
uint256 usdtReserve = Tusdt.balanceOf(address(this));
uint256 newReserve = usdtReserve.mul(10**_decimals).div(startPrice);
uint256 temp;
if (newReserve>tokenReserve) {
temp = newReserve.sub(tokenReserve);
Token.mint(address(this),temp);
temp = tokenReserve.sub(newReserve);
Token.burn(temp);
}
return newReserve;
}
| 5,352,335 |
./full_match/1/0x6CB6107f84c7559707AF026C9ED83cfc5DCb72E9/sources/contracts/USDM.sol
|
Converts an amount of tokens to shares. amount The amount of tokens to convert. return The equivalent amount of shares. Note: All rounding errors should be rounded down in the interest of the protocol's safety. Token transfers, including mint and burn operations, may require a rounding, leading to potential transferring at most one GWEI less than expected aggregated over a long period of time./
|
function convertToShares(uint256 amount) public view returns (uint256) {
return (amount * _BASE) / rewardMultiplier;
}
| 9,652,321 |
pragma solidity ^0.5.1;
import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import { ERC1155 } from "./ERC1155/ERC1155.sol";
import { CTHelpers } from "./CTHelpers.sol";
contract ConditionalTokens is ERC1155 {
/// @dev Emitted upon the successful preparation of a condition.
/// @param conditionId The condition's ID. This ID may be derived from the other three parameters via ``keccak256(abi.encodePacked(oracle, questionId, outcomeSlotCount))``.
/// @param oracle The account assigned to report the result for the prepared condition.
/// @param questionId An identifier for the question to be answered by the oracle.
/// @param outcomeSlotCount The number of outcome slots which should be used for this condition. Must not exceed 256.
event ConditionPreparation(
bytes32 indexed conditionId,
address indexed oracle,
bytes32 indexed questionId,
uint outcomeSlotCount
);
event ConditionResolution(
bytes32 indexed conditionId,
address indexed oracle,
bytes32 indexed questionId,
uint outcomeSlotCount,
uint[] payoutNumerators
);
/// @dev Emitted when a position is successfully split.
event PositionSplit(
address indexed stakeholder,
IERC20 collateralToken,
bytes32 indexed parentCollectionId,
bytes32 indexed conditionId,
uint[] partition,
uint amount
);
/// @dev Emitted when positions are successfully merged.
event PositionsMerge(
address indexed stakeholder,
IERC20 collateralToken,
bytes32 indexed parentCollectionId,
bytes32 indexed conditionId,
uint[] partition,
uint amount
);
event PayoutRedemption(
address indexed redeemer,
IERC20 indexed collateralToken,
bytes32 indexed parentCollectionId,
bytes32 conditionId,
uint[] indexSets,
uint payout
);
/// Mapping key is an condition ID. Value represents numerators of the payout vector associated with the condition. This array is initialized with a length equal to the outcome slot count. E.g. Condition with 3 outcomes [A, B, C] and two of those correct [0.5, 0.5, 0]. In Ethereum there are no decimal values, so here, 0.5 is represented by fractions like 1/2 == 0.5. That's why we need numerator and denominator values. Payout numerators are also used as a check of initialization. If the numerators array is empty (has length zero), the condition was not created/prepared. See getOutcomeSlotCount.
mapping(bytes32 => uint[]) public payoutNumerators;
/// Denominator is also used for checking if the condition has been resolved. If the denominator is non-zero, then the condition has been resolved.
mapping(bytes32 => uint) public payoutDenominator;
/// @dev This function prepares a condition by initializing a payout vector associated with the condition.
/// @param oracle The account assigned to report the result for the prepared condition.
/// @param questionId An identifier for the question to be answered by the oracle.
/// @param outcomeSlotCount The number of outcome slots which should be used for this condition. Must not exceed 256.
function prepareCondition(address oracle, bytes32 questionId, uint outcomeSlotCount) external {
// Limit of 256 because we use a partition array that is a number of 256 bits.
require(outcomeSlotCount <= 256, "too many outcome slots");
require(outcomeSlotCount > 1, "there should be more than one outcome slot");
bytes32 conditionId = CTHelpers.getConditionId(oracle, questionId, outcomeSlotCount);
require(payoutNumerators[conditionId].length == 0, "condition already prepared");
payoutNumerators[conditionId] = new uint[](outcomeSlotCount);
emit ConditionPreparation(conditionId, oracle, questionId, outcomeSlotCount);
}
/// @dev Called by the oracle for reporting results of conditions. Will set the payout vector for the condition with the ID ``keccak256(abi.encodePacked(oracle, questionId, outcomeSlotCount))``, where oracle is the message sender, questionId is one of the parameters of this function, and outcomeSlotCount is the length of the payouts parameter, which contains the payoutNumerators for each outcome slot of the condition.
/// @param questionId The question ID the oracle is answering for
/// @param payouts The oracle's answer
function reportPayouts(bytes32 questionId, uint[] calldata payouts) external {
uint outcomeSlotCount = payouts.length;
require(outcomeSlotCount > 1, "there should be more than one outcome slot");
// IMPORTANT, the oracle is enforced to be the sender because it's part of the hash.
bytes32 conditionId = CTHelpers.getConditionId(msg.sender, questionId, outcomeSlotCount);
require(payoutNumerators[conditionId].length == outcomeSlotCount, "condition not prepared or found");
require(payoutDenominator[conditionId] == 0, "payout denominator already set");
uint den = 0;
for (uint i = 0; i < outcomeSlotCount; i++) {
uint num = payouts[i];
den = den.add(num);
require(payoutNumerators[conditionId][i] == 0, "payout numerator already set");
payoutNumerators[conditionId][i] = num;
}
require(den > 0, "payout is all zeroes");
payoutDenominator[conditionId] = den;
emit ConditionResolution(conditionId, msg.sender, questionId, outcomeSlotCount, payoutNumerators[conditionId]);
}
/// @dev This function splits a position. If splitting from the collateral, this contract will attempt to transfer `amount` collateral from the message sender to itself. Otherwise, this contract will burn `amount` stake held by the message sender in the position being split worth of EIP 1155 tokens. Regardless, if successful, `amount` stake will be minted in the split target positions. If any of the transfers, mints, or burns fail, the transaction will revert. The transaction will also revert if the given partition is trivial, invalid, or refers to more slots than the condition is prepared with.
/// @param collateralToken The address of the positions' backing collateral token.
/// @param parentCollectionId The ID of the outcome collections common to the position being split and the split target positions. May be null, in which only the collateral is shared.
/// @param conditionId The ID of the condition to split on.
/// @param partition An array of disjoint index sets representing a nontrivial partition of the outcome slots of the given condition. E.g. A|B and C but not A|B and B|C (is not disjoint). Each element's a number which, together with the condition, represents the outcome collection. E.g. 0b110 is A|B, 0b010 is B, etc.
/// @param amount The amount of collateral or stake to split.
function splitPosition(
IERC20 collateralToken,
bytes32 parentCollectionId,
bytes32 conditionId,
uint[] calldata partition,
uint amount
) external {
require(partition.length > 1, "got empty or singleton partition");
uint outcomeSlotCount = payoutNumerators[conditionId].length;
require(outcomeSlotCount > 0, "condition not prepared yet");
// For a condition with 4 outcomes fullIndexSet's 0b1111; for 5 it's 0b11111...
uint fullIndexSet = (1 << outcomeSlotCount) - 1;
// freeIndexSet starts as the full collection
uint freeIndexSet = fullIndexSet;
// This loop checks that all condition sets are disjoint (the same outcome is not part of more than 1 set)
uint[] memory positionIds = new uint[](partition.length);
uint[] memory amounts = new uint[](partition.length);
for (uint i = 0; i < partition.length; i++) {
uint indexSet = partition[i];
require(indexSet > 0 && indexSet < fullIndexSet, "got invalid index set");
require((indexSet & freeIndexSet) == indexSet, "partition not disjoint");
freeIndexSet ^= indexSet;
positionIds[i] = CTHelpers.getPositionId(collateralToken, CTHelpers.getCollectionId(parentCollectionId, conditionId, indexSet));
amounts[i] = amount;
}
if (freeIndexSet == 0) {
// Partitioning the full set of outcomes for the condition in this branch
if (parentCollectionId == bytes32(0)) {
require(collateralToken.transferFrom(msg.sender, address(this), amount), "could not receive collateral tokens");
} else {
_burn(
msg.sender,
CTHelpers.getPositionId(collateralToken, parentCollectionId),
amount
);
}
} else {
// Partitioning a subset of outcomes for the condition in this branch.
// For example, for a condition with three outcomes A, B, and C, this branch
// allows the splitting of a position $:(A|C) to positions $:(A) and $:(C).
_burn(
msg.sender,
CTHelpers.getPositionId(collateralToken,
CTHelpers.getCollectionId(parentCollectionId, conditionId, fullIndexSet ^ freeIndexSet)),
amount
);
}
_batchMint(
msg.sender,
// position ID is the ERC 1155 token ID
positionIds,
amounts,
""
);
emit PositionSplit(msg.sender, collateralToken, parentCollectionId, conditionId, partition, amount);
}
function mergePositions(
IERC20 collateralToken,
bytes32 parentCollectionId,
bytes32 conditionId,
uint[] calldata partition,
uint amount
) external {
require(partition.length > 1, "got empty or singleton partition");
uint outcomeSlotCount = payoutNumerators[conditionId].length;
require(outcomeSlotCount > 0, "condition not prepared yet");
uint fullIndexSet = (1 << outcomeSlotCount) - 1;
uint freeIndexSet = fullIndexSet;
uint[] memory positionIds = new uint[](partition.length);
uint[] memory amounts = new uint[](partition.length);
for (uint i = 0; i < partition.length; i++) {
uint indexSet = partition[i];
require(indexSet > 0 && indexSet < fullIndexSet, "got invalid index set");
require((indexSet & freeIndexSet) == indexSet, "partition not disjoint");
freeIndexSet ^= indexSet;
positionIds[i] = CTHelpers.getPositionId(collateralToken, CTHelpers.getCollectionId(parentCollectionId, conditionId, indexSet));
amounts[i] = amount;
}
_batchBurn(
msg.sender,
positionIds,
amounts
);
if (freeIndexSet == 0) {
if (parentCollectionId == bytes32(0)) {
require(collateralToken.transfer(msg.sender, amount), "could not send collateral tokens");
} else {
_mint(
msg.sender,
CTHelpers.getPositionId(collateralToken, parentCollectionId),
amount,
""
);
}
} else {
_mint(
msg.sender,
CTHelpers.getPositionId(collateralToken,
CTHelpers.getCollectionId(parentCollectionId, conditionId, fullIndexSet ^ freeIndexSet)),
amount,
""
);
}
emit PositionsMerge(msg.sender, collateralToken, parentCollectionId, conditionId, partition, amount);
}
function redeemPositions(IERC20 collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint[] memory indexSets) public {
uint den = payoutDenominator[conditionId];
require(den > 0, "result for condition not received yet");
uint outcomeSlotCount = payoutNumerators[conditionId].length;
require(outcomeSlotCount > 0, "condition not prepared yet");
uint totalPayout = 0;
uint fullIndexSet = (1 << outcomeSlotCount) - 1;
for (uint i = 0; i < indexSets.length; i++) {
uint indexSet = indexSets[i];
require(indexSet > 0 && indexSet < fullIndexSet, "got invalid index set");
uint positionId = CTHelpers.getPositionId(collateralToken,
CTHelpers.getCollectionId(parentCollectionId, conditionId, indexSet));
uint payoutNumerator = 0;
for (uint j = 0; j < outcomeSlotCount; j++) {
if (indexSet & (1 << j) != 0) {
payoutNumerator = payoutNumerator.add(payoutNumerators[conditionId][j]);
}
}
uint payoutStake = balanceOf(msg.sender, positionId);
if (payoutStake > 0) {
totalPayout = totalPayout.add(payoutStake.mul(payoutNumerator).div(den));
_burn(msg.sender, positionId, payoutStake);
}
}
if (totalPayout > 0) {
if (parentCollectionId == bytes32(0)) {
require(collateralToken.transfer(msg.sender, totalPayout), "could not transfer payout to message sender");
} else {
_mint(msg.sender, CTHelpers.getPositionId(collateralToken, parentCollectionId), totalPayout, "");
}
}
emit PayoutRedemption(msg.sender, collateralToken, parentCollectionId, conditionId, indexSets, totalPayout);
}
/// @dev Gets the outcome slot count of a condition.
/// @param conditionId ID of the condition.
/// @return Number of outcome slots associated with a condition, or zero if condition has not been prepared yet.
function getOutcomeSlotCount(bytes32 conditionId) external view returns (uint) {
return payoutNumerators[conditionId].length;
}
/// @dev Constructs a condition ID from an oracle, a question ID, and the outcome slot count for the question.
/// @param oracle The account assigned to report the result for the prepared condition.
/// @param questionId An identifier for the question to be answered by the oracle.
/// @param outcomeSlotCount The number of outcome slots which should be used for this condition. Must not exceed 256.
function getConditionId(address oracle, bytes32 questionId, uint outcomeSlotCount) external pure returns (bytes32) {
return CTHelpers.getConditionId(oracle, questionId, outcomeSlotCount);
}
/// @dev Constructs an outcome collection ID from a parent collection and an outcome collection.
/// @param parentCollectionId Collection ID of the parent outcome collection, or bytes32(0) if there's no parent.
/// @param conditionId Condition ID of the outcome collection to combine with the parent outcome collection.
/// @param indexSet Index set of the outcome collection to combine with the parent outcome collection.
function getCollectionId(bytes32 parentCollectionId, bytes32 conditionId, uint indexSet) external view returns (bytes32) {
return CTHelpers.getCollectionId(parentCollectionId, conditionId, indexSet);
}
/// @dev Constructs a position ID from a collateral token and an outcome collection. These IDs are used as the ERC-1155 ID for this contract.
/// @param collateralToken Collateral token which backs the position.
/// @param collectionId ID of the outcome collection associated with this position.
function getPositionId(IERC20 collateralToken, bytes32 collectionId) external pure returns (uint) {
return CTHelpers.getPositionId(collateralToken, collectionId);
}
}
|
Called by the oracle for reporting results of conditions. Will set the payout vector for the condition with the ID ``keccak256(abi.encodePacked(oracle, questionId, outcomeSlotCount))``, where oracle is the message sender, questionId is one of the parameters of this function, and outcomeSlotCount is the length of the payouts parameter, which contains the payoutNumerators for each outcome slot of the condition. questionId The question ID the oracle is answering for payouts The oracle's answer IMPORTANT, the oracle is enforced to be the sender because it's part of the hash.
|
function reportPayouts(bytes32 questionId, uint[] calldata payouts) external {
uint outcomeSlotCount = payouts.length;
require(outcomeSlotCount > 1, "there should be more than one outcome slot");
bytes32 conditionId = CTHelpers.getConditionId(msg.sender, questionId, outcomeSlotCount);
require(payoutNumerators[conditionId].length == outcomeSlotCount, "condition not prepared or found");
require(payoutDenominator[conditionId] == 0, "payout denominator already set");
uint den = 0;
for (uint i = 0; i < outcomeSlotCount; i++) {
uint num = payouts[i];
den = den.add(num);
require(payoutNumerators[conditionId][i] == 0, "payout numerator already set");
payoutNumerators[conditionId][i] = num;
}
require(den > 0, "payout is all zeroes");
payoutDenominator[conditionId] = den;
emit ConditionResolution(conditionId, msg.sender, questionId, outcomeSlotCount, payoutNumerators[conditionId]);
}
| 1,014,875 |
pragma solidity ^0.8.0;
import "../lib/Ownable.sol";
import "./BaseDepositLocker.sol";
abstract contract BaseValidatorAuction is Ownable {
uint constant MAX_UINT = ~uint(0);
// auction constants set on deployment
uint public auctionDurationInDays;
uint public startPrice;
uint public minimalNumberOfParticipants;
uint public maximalNumberOfParticipants;
AuctionState public auctionState;
BaseDepositLocker public depositLocker;
mapping(address => bool) public whitelist;
mapping(address => uint) public bids;
address[] public bidders;
uint public startTime;
uint public closeTime;
uint public lowestSlotPrice;
event BidSubmitted(
address bidder,
uint bidValue,
uint slotPrice,
uint timestamp
);
event AddressWhitelisted(address whitelistedAddress);
event AuctionDeployed(
uint startPrice,
uint auctionDurationInDays,
uint minimalNumberOfParticipants,
uint maximalNumberOfParticipants
);
event AuctionStarted(uint startTime);
event AuctionDepositPending(
uint closeTime,
uint lowestSlotPrice,
uint totalParticipants
);
event AuctionEnded(
uint closeTime,
uint lowestSlotPrice,
uint totalParticipants
);
event AuctionFailed(uint closeTime, uint numberOfBidders);
enum AuctionState {
Deployed,
Started,
DepositPending, /* all slots sold, someone needs to call depositBids */
Ended,
Failed
}
modifier stateIs(AuctionState state) {
require(
auctionState == state,
"Auction is not in the proper state for desired action."
);
_;
}
constructor(
uint _startPriceInWei,
uint _auctionDurationInDays,
uint _minimalNumberOfParticipants,
uint _maximalNumberOfParticipants,
BaseDepositLocker _depositLocker
) {
require(
_auctionDurationInDays > 0,
"Duration of auction must be greater than 0"
);
require(
_auctionDurationInDays < 100 * 365,
"Duration of auction must be less than 100 years"
);
require(
_minimalNumberOfParticipants > 0,
"Minimal number of participants must be greater than 0"
);
require(
_maximalNumberOfParticipants > 0,
"Number of participants must be greater than 0"
);
require(
_minimalNumberOfParticipants <= _maximalNumberOfParticipants,
"The minimal number of participants must be smaller than the maximal number of participants."
);
require(_startPriceInWei > 0, "The start price has to be > 0");
require(
// To prevent overflows
_startPriceInWei < 10**30,
"The start price is too big."
);
startPrice = _startPriceInWei;
auctionDurationInDays = _auctionDurationInDays;
maximalNumberOfParticipants = _maximalNumberOfParticipants;
minimalNumberOfParticipants = _minimalNumberOfParticipants;
depositLocker = _depositLocker;
lowestSlotPrice = MAX_UINT;
emit AuctionDeployed(
startPrice,
auctionDurationInDays,
_minimalNumberOfParticipants,
_maximalNumberOfParticipants
);
auctionState = AuctionState.Deployed;
}
receive() external payable stateIs(AuctionState.Started) {
bid();
}
function bid() public payable stateIs(AuctionState.Started) {
require(block.timestamp > startTime, "It is too early to bid.");
require(
block.timestamp <= startTime + auctionDurationInDays * 1 days,
"Auction has already ended."
);
uint slotPrice = currentPrice();
require(whitelist[msg.sender], "The sender is not whitelisted.");
require(!isSenderContract(), "The sender cannot be a contract.");
require(
bidders.length < maximalNumberOfParticipants,
"The limit of participants has already been reached."
);
require(bids[msg.sender] == 0, "The sender has already bid.");
uint bidAmount = _getBidAmount(slotPrice);
require(bidAmount > 0, "The bid amount has to be > 0");
bids[msg.sender] = bidAmount;
bidders.push(msg.sender);
if (slotPrice < lowestSlotPrice) {
lowestSlotPrice = slotPrice;
}
depositLocker.registerDepositor(msg.sender);
emit BidSubmitted(msg.sender, bidAmount, slotPrice, block.timestamp);
if (bidders.length == maximalNumberOfParticipants) {
transitionToDepositPending();
}
_receiveBid(bidAmount);
}
function startAuction() public onlyOwner stateIs(AuctionState.Deployed) {
require(
depositLocker.initialized(),
"The deposit locker contract is not initialized"
);
auctionState = AuctionState.Started;
startTime = block.timestamp;
emit AuctionStarted(block.timestamp);
}
function depositBids() public stateIs(AuctionState.DepositPending) {
auctionState = AuctionState.Ended;
_deposit(lowestSlotPrice, lowestSlotPrice * bidders.length);
emit AuctionEnded(closeTime, lowestSlotPrice, bidders.length);
}
function closeAuction() public stateIs(AuctionState.Started) {
require(
block.timestamp > startTime + auctionDurationInDays * 1 days,
"The auction cannot be closed this early."
);
assert(bidders.length < maximalNumberOfParticipants);
if (bidders.length >= minimalNumberOfParticipants) {
transitionToDepositPending();
} else {
transitionToAuctionFailed();
}
}
function addToWhitelist(address[] memory addressesToWhitelist)
public
onlyOwner
stateIs(AuctionState.Deployed)
{
for (uint32 i = 0; i < addressesToWhitelist.length; i++) {
whitelist[addressesToWhitelist[i]] = true;
emit AddressWhitelisted(addressesToWhitelist[i]);
}
}
function withdraw() public {
require(
auctionState == AuctionState.Ended ||
auctionState == AuctionState.Failed,
"You cannot withdraw before the auction is ended or it failed."
);
if (auctionState == AuctionState.Ended) {
withdrawAfterAuctionEnded();
} else if (auctionState == AuctionState.Failed) {
withdrawAfterAuctionFailed();
} else {
assert(false); // Should be unreachable
}
}
function currentPrice()
public
view
virtual
stateIs(AuctionState.Started)
returns (uint)
{
assert(block.timestamp >= startTime);
uint secondsSinceStart = (block.timestamp - startTime);
return priceAtElapsedTime(secondsSinceStart);
}
function priceAtElapsedTime(uint secondsSinceStart)
public
view
returns (uint)
{
// To prevent overflows
require(
secondsSinceStart < 100 * 365 days,
"Times longer than 100 years are not supported."
);
uint msSinceStart = 1000 * secondsSinceStart;
uint relativeAuctionTime = msSinceStart / auctionDurationInDays;
uint decayDivisor = 746571428571;
uint decay = relativeAuctionTime**3 / decayDivisor;
uint price =
(startPrice * (1 + relativeAuctionTime)) /
(1 + relativeAuctionTime + decay);
return price;
}
function withdrawAfterAuctionEnded() internal stateIs(AuctionState.Ended) {
require(
bids[msg.sender] > lowestSlotPrice,
"The sender has nothing to withdraw."
);
uint valueToWithdraw = bids[msg.sender] - lowestSlotPrice;
assert(valueToWithdraw <= bids[msg.sender]);
bids[msg.sender] = lowestSlotPrice;
_transfer(payable(msg.sender), valueToWithdraw);
}
function withdrawAfterAuctionFailed()
internal
stateIs(AuctionState.Failed)
{
require(bids[msg.sender] > 0, "The sender has nothing to withdraw.");
uint valueToWithdraw = bids[msg.sender];
bids[msg.sender] = 0;
_transfer(payable(msg.sender), valueToWithdraw);
}
function transitionToDepositPending()
internal
stateIs(AuctionState.Started)
{
auctionState = AuctionState.DepositPending;
closeTime = block.timestamp;
emit AuctionDepositPending(closeTime, lowestSlotPrice, bidders.length);
}
function transitionToAuctionFailed()
internal
stateIs(AuctionState.Started)
{
auctionState = AuctionState.Failed;
closeTime = block.timestamp;
emit AuctionFailed(closeTime, bidders.length);
}
function isSenderContract() internal view returns (bool isContract) {
uint32 size;
address sender = msg.sender;
// solium-disable-next-line security/no-inline-assembly
assembly {
size := extcodesize(sender)
}
return (size > 0);
}
/// Hooks for derived contracts to process bids
function _receiveBid(uint amount) internal virtual;
function _transfer(address payable recipient, uint amount) internal virtual;
function _deposit(uint slotPrice, uint totalValue) internal virtual;
function _getBidAmount(uint slotPrice) internal view virtual returns (uint);
}
// SPDX-License-Identifier: MIT
|
solium-disable-next-line security/no-inline-assembly
|
function isSenderContract() internal view returns (bool isContract) {
uint32 size;
address sender = msg.sender;
assembly {
size := extcodesize(sender)
}
return (size > 0);
}
| 1,779,336 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.6.0 <8.0.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./Serializer.sol";
/// @notice Submission of remote chain block header.
struct HeaderSubmission {
// Block header
Header header;
// Submitter
address payable submitter;
// Ethereum block number submission was made
uint256 blockNumber;
// Simple hash of previous block's commit in ABI encoded format
bytes32 lastCommitHash;
}
/// @title Optimistic rollup of a remote chain's Tendermint consensus.
contract Tendermint_ORU {
using Serializer for Header;
using Serializer for Signature;
using Serializer for CommitSig;
using Serializer for Commit;
using Serializer for LightBlock;
////////////////////////////////////
// Events
////////////////////////////////////
event BlockSubmitted(
LightBlock lightBlock,
bytes32 indexed headerHash,
uint256 indexed height,
HeaderSubmission headerSubmission
);
////////////////////////////////////
// Immutable fields
////////////////////////////////////
/// @notice Remote chain's genesis hash.
bytes32 public immutable _genesisHash;
/// @notice Genesis submission hash.
bytes32 public immutable _genesisSubmissionHash;
/// @notice Bond size.
uint256 public immutable _bondSize;
/// @notice Timeout for fraud proofs, in Ethereum blocks.
uint256 public immutable _fraudTimeout;
////////////////////////////////////
// Mutable fields (storage)
////////////////////////////////////
/// @notice Hashes of submissions of remote chain's block headers.
/// @dev header hash => header submission hash
mapping(bytes32 => bytes32) public _headerSubmissionHashes;
/// @notice Height of submissions.
/// @dev header submission hash => height
mapping(bytes32 => uint64) public _headerHeights;
/// @notice If a block is not finalized.
/// @dev header hash => is not finalized
mapping(bytes32 => bool) public _isNotFinalized;
/// @notice Header hash of the tip block.
bytes32 public _tipHash;
////////////////////////////////////
// Constructor
////////////////////////////////////
constructor(
bytes32 genesisHash,
bytes32 genesisSubmissionHash,
uint256 bondSize,
uint256 fraudTimeout
) public {
_genesisHash = genesisHash;
_genesisSubmissionHash = genesisSubmissionHash;
_bondSize = bondSize;
_fraudTimeout = fraudTimeout;
// The genesis block is already finalized implicitly, so we simply set the height to 1
_headerHeights[genesisSubmissionHash] = 1;
// Set the tip hash
_tipHash = genesisHash;
}
////////////////////////////////////
// External functions
////////////////////////////////////
/// @notice Submit a new bare block, placing a bond.
function submitBlock(LightBlock memory lightBlock, bytes32 prevSubmissionHash) external payable {
// Must send _bondSize ETH to submit a block
require(msg.value == _bondSize);
// Previous block header hash must be the tip
require(lightBlock.header.lastBlockID == _tipHash);
// Height must increment
// Note: orphaned blocks be pruned before submitting new blocks since
// this check does not account for forks.
require(lightBlock.header.height == SafeMath.add(_headerHeights[prevSubmissionHash], 1));
// Take simple hash of commit for previous block
bytes32 lastCommitHash = keccak256(lightBlock.lastCommit.serialize());
// Serialize header
bytes memory serializedHeader = lightBlock.header.serialize();
// Hash serialized header
bytes32 headerHash = keccak256(serializedHeader);
// Insert header as new tip
HeaderSubmission memory headerSubmission = HeaderSubmission(
lightBlock.header,
msg.sender,
block.number,
lastCommitHash
);
bytes32 headerSubmissionHash = keccak256(abi.encode(headerSubmission));
_headerSubmissionHashes[headerHash] = headerSubmissionHash;
_headerHeights[headerSubmissionHash] = lightBlock.header.height;
_isNotFinalized[headerHash] = true;
_tipHash = headerHash;
emit BlockSubmitted(lightBlock, headerHash, lightBlock.header.height, headerSubmission);
}
/// @notice Prove a block was invalid, reverting it and orphaning its descendents.
function proveFraud(
bytes32 headerHash,
HeaderSubmission calldata headerSubmission,
HeaderSubmission calldata tipSubmission,
Commit memory commit
) external {
// Check submission against storage
bytes32 headerSubmissionHash = keccak256(abi.encode(headerSubmission));
require(headerSubmissionHash == _headerSubmissionHashes[headerHash]);
// Block must not be finalized yet
require(_isNotFinalized[headerHash]);
// Block must be at most the same height as the tip
// Note: orphaned blocks be pruned before submitting new blocks since
// this check does not account for forks.
require(keccak256(abi.encode(tipSubmission)) == _headerSubmissionHashes[_tipHash]);
require(headerSubmission.header.height <= tipSubmission.header.height);
// TODO serialize and Merkleize commit
// TODO compare root against stored root
// TODO process commit, check at least 2/3 of voting power
// Reset storage
delete _headerSubmissionHashes[headerHash];
delete _headerHeights[headerSubmissionHash];
delete _isNotFinalized[headerHash];
// Roll back the tip
_tipHash = headerSubmission.header.lastBlockID;
// Return half of bond to prover
msg.sender.transfer(SafeMath.div(_bondSize, 2));
}
/// @notice Finalize blocks, returning the bond to the submitter.
function finalizeBlocks(bytes32[] calldata headerHashes, HeaderSubmission[] calldata headerSubmissions) external {
for (uint256 i = 0; i < headerHashes.length; i++) {
bytes32 headerHash = headerHashes[i];
HeaderSubmission memory headerSubmission = headerSubmissions[i];
// Check submission against storage
bytes32 headerSubmissionHash = keccak256(abi.encode(headerSubmission));
require(headerSubmissionHash == _headerSubmissionHashes[headerHash]);
// Block must not be finalized yet
require(_isNotFinalized[headerHash]);
// Timeout must be expired in order to finalize a block
require(block.number > SafeMath.add(headerSubmission.blockNumber, _fraudTimeout));
// Reset storage (height is kept!)
delete _headerSubmissionHashes[headerHash];
delete _isNotFinalized[headerHash];
// Return bond to submitter
headerSubmission.submitter.transfer(_bondSize);
}
}
/// @notice Prune blocks orphaned in a reversion.
/// @dev Orphaned blocks must be pruned before submitting new blocks.
function pruneBlocks(bytes32[] calldata headerHashes, HeaderSubmission[] calldata headerSubmissions) external {
for (uint256 i = 0; i < headerHashes.length; i++) {
bytes32 headerHash = headerHashes[i];
HeaderSubmission memory headerSubmission = headerSubmissions[i];
// Check submission against storage
bytes32 headerSubmissionHash = keccak256(abi.encode(headerSubmission));
require(headerSubmissionHash == _headerSubmissionHashes[headerHash]);
// Block must not be finalized yet
require(_isNotFinalized[headerHash]);
// Previous block must be orphaned
require(_headerSubmissionHashes[headerSubmission.header.lastBlockID] == 0);
// Reset storage
delete _headerSubmissionHashes[headerHash];
delete _headerHeights[headerSubmissionHash];
delete _isNotFinalized[headerHash];
// Return half of bond to pruner
msg.sender.transfer(SafeMath.div(_bondSize, 2));
}
}
}
|
Prune blocks orphaned in a reversion. Orphaned blocks must be pruned before submitting new blocks. Check submission against storage Block must not be finalized yet Previous block must be orphaned Reset storage Return half of bond to pruner
|
function pruneBlocks(bytes32[] calldata headerHashes, HeaderSubmission[] calldata headerSubmissions) external {
for (uint256 i = 0; i < headerHashes.length; i++) {
bytes32 headerHash = headerHashes[i];
HeaderSubmission memory headerSubmission = headerSubmissions[i];
bytes32 headerSubmissionHash = keccak256(abi.encode(headerSubmission));
require(headerSubmissionHash == _headerSubmissionHashes[headerHash]);
require(_isNotFinalized[headerHash]);
require(_headerSubmissionHashes[headerSubmission.header.lastBlockID] == 0);
delete _headerSubmissionHashes[headerHash];
delete _headerHeights[headerSubmissionHash];
delete _isNotFinalized[headerHash];
msg.sender.transfer(SafeMath.div(_bondSize, 2));
}
}
| 12,764,658 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
}
function __AccessControlEnumerable_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "./interfaces/ICandyToken.sol";
contract UninterestedUnicornsV2 is
AccessControlEnumerableUpgradeable,
PausableUpgradeable,
OwnableUpgradeable,
ERC721Upgradeable
{
using CountersUpgradeable for CountersUpgradeable.Counter;
using StringsUpgradeable for uint256;
using ECDSAUpgradeable for bytes32;
struct Parents {
uint16 parent_1;
uint16 parent_2;
}
// Stores quantity of UUs left in a season
uint256 public QUANTITY_LEFT;
// Breeding Information
uint256 public BREEDING_COST; // UCD Breeding Cost
uint256 public BREEDING_COST_ETH; // ETH Breeding cost
uint256[] public BREEDING_DISCOUNT_THRESHOLD; // UCD to hold for discount
uint256[] public BREEDING_DISCOUNT_PERC; // UCD to hold for discount
// Signers
address private BREED_SIGNER;
address private WHITELIST_SIGNER;
// External Contracts
ICandyToken public CANDY_TOKEN;
// GNOSIS SAFE
address public TREASURY;
// Passive Rewards
uint256 public REWARDS_PER_DAY;
mapping(uint256 => uint256) public lastClaim;
// Private Variables
CountersUpgradeable.Counter private _tokenIds;
string private baseTokenURI;
// UU Status
mapping(uint256 => bool) private isBred; // Mapping that determines if the UUv1 is Bred
// Toggles
bool private breedingOpen;
bool private presaleOpen;
bool private publicOpen;
// Mint Caps
mapping(address => uint8) private privateSaleMintedAmount;
mapping(address => uint8) private publicSaleMintedAmount;
// Nonce
mapping(bytes => bool) private _nonceUsed;
// Parent Mapping
mapping(uint256 => Parents) private _parents;
// Reserve Storage (important: New variables should be declared below)
uint256[50] private ______gap;
// ------------------------ EVENTS ----------------------------
event Minted(address indexed minter, uint256 indexed tokenId);
event Breed(
address indexed minter,
uint256 tokenId,
uint256 parent_1_tokenId,
uint256 parent_2_tokenId
);
event RewardsClaimed(
address indexed user,
uint256 tokenId,
uint256 amount,
uint256 timestamp
);
// ---------------------- MODIFIERS ---------------------------
/// @dev Only EOA modifier
modifier onlyEOA() {
require(msg.sender == tx.origin, "UUv2: Only EOA");
_;
}
function __UUv2_init(
address owner,
address _treasury,
address _breedSigner,
address _whitelistSigner
) public initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained("UninterestedUnicornsV2", "UUv2");
__Ownable_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
__Pausable_init_unchained();
transferOwnership(owner);
TREASURY = _treasury;
REWARDS_PER_DAY = 2 ether;
BREEDING_COST = 1000 ether;
BREEDING_COST_ETH = 0.1 ether;
BREEDING_DISCOUNT_THRESHOLD = [10000 ether, 5000 ether];
BREEDING_DISCOUNT_PERC = [75, 90]; // Percentage Discount
BREED_SIGNER = _breedSigner;
WHITELIST_SIGNER = _whitelistSigner;
QUANTITY_LEFT = 5000;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); // To revoke access after deployment
grantRole(DEFAULT_ADMIN_ROLE, TREASURY);
_setBaseURI(
"https://lit-island-00614.herokuapp.com/api/v1/uuv2/chromosomes/"
);
}
// ------------------------- USER FUNCTION ---------------------------
/// @dev Takes the input of 2 genesis UU ids and breed them together
/// @dev Ownership verication is done off-chain and signed by BREED_SIGNER
function breed(
uint16 parent_1_tokenId,
uint16 parent_2_tokenId,
bytes memory nonce,
bytes memory signature
) public {
require(
breedSigned(
msg.sender,
nonce,
signature,
parent_1_tokenId,
parent_2_tokenId
),
"UUv2: Invalid Signature"
);
require(isBreedingOpen(), "UUv2: Breeding is not open");
require(
CANDY_TOKEN.balanceOf(msg.sender) > BREEDING_COST,
"UUv2: Insufficient UCD for breeding"
);
require(QUANTITY_LEFT != 0, "UUv2: No more UUs available");
require(
!isBred[parent_1_tokenId] && !isBred[parent_2_tokenId],
"UUv2: UUs have been bred before!"
);
// Reduce Quantity Left
QUANTITY_LEFT -= 1;
// Increase Token ID
_tokenIds.increment();
isBred[parent_1_tokenId] = true;
isBred[parent_2_tokenId] = true;
// Burn UCD Token
CANDY_TOKEN.burn(msg.sender, BREEDING_COST);
// Store Parent Id
_parents[_tokenIds.current()] = Parents(
parent_1_tokenId,
parent_2_tokenId
);
// Set Last Claim
lastClaim[_tokenIds.current()] = block.timestamp;
// Mint
_mint(msg.sender, _tokenIds.current());
emit Breed(
_msgSender(),
_tokenIds.current(),
parent_1_tokenId,
parent_2_tokenId
);
}
/// @dev Mint a random UUv2. Whitelisted addresses only
/// @dev Whitelist is done off-chain and signed by WHITELIST_SIGNER
function whitelistMint(bytes memory nonce, bytes memory signature)
public
payable
onlyEOA
{
require(isPresaleOpen(), "UUv2: Presale Mint not open!");
require(!_nonceUsed[nonce], "UUv2: Nonce was used");
require(
whitelistSigned(msg.sender, nonce, signature),
"UUv2: Invalid signature"
);
require(
privateSaleMintedAmount[msg.sender] < 1,
"UUv2: Presale Limit Exceeded!"
);
require(
msg.value == getETHPrice(msg.sender),
"UUv2: Insufficient ETH!"
);
require(QUANTITY_LEFT != 0, "UUv2: No more UUs available");
QUANTITY_LEFT -= 1;
_tokenIds.increment();
// Set Last Claim
lastClaim[_tokenIds.current()] = block.timestamp;
_mint(msg.sender, _tokenIds.current());
(bool success, ) = TREASURY.call{value: msg.value}(""); // forward amount to treasury wallet
require(success, "PropertyNFT: Unable to forward message to treasury!");
}
/// @dev Mint a random UUv2
function mint(uint256 _amount) public payable onlyEOA {
require(isPublicOpen(), "UUv2: Public Mint not open!");
require(_amount <= 5, "UUv2: Maximum of 5 mints per transaction!");
require(
publicSaleMintedAmount[msg.sender] + _amount < 5,
"UUv2: Public Limit Exceeded!"
);
require(
msg.value == getETHPrice(msg.sender) * _amount,
"UUv2: Insufficient ETH!"
);
for (uint256 i; i < _amount; i++) {
require(QUANTITY_LEFT != 0, "UUv2: No more UUs available");
QUANTITY_LEFT -= 1;
_tokenIds.increment();
// Set Last Claim
lastClaim[_tokenIds.current()] = block.timestamp;
_mint(msg.sender, _tokenIds.current());
}
(bool success, ) = TREASURY.call{value: msg.value}(""); // forward amount to treasury wallet
require(success, "PropertyNFT: Unable to forward message to treasury!");
}
/// @dev Allow UUv2 Holders to claim UCD Rewards
function claimRewards(uint256 tokenId) public {
require(
ownerOf(tokenId) == msg.sender,
"UUv2: Claimant is not the owner!"
);
uint256 amount = calculateRewards(tokenId);
// Update Last Claim
lastClaim[tokenId] = block.timestamp;
CANDY_TOKEN.mint(msg.sender, amount);
emit RewardsClaimed(msg.sender, tokenId, amount, block.timestamp);
}
/// @dev Allow UUv2 Holders to claim UCD Rewards for a array of tokens
function claimRewardsMultiple(uint256[] memory tokenIds) public {
uint256 amount = 0; // Store total amount
// Update Last Claim
for (uint256 i = 0; i < tokenIds.length; i++) {
require(
ownerOf(tokenIds[i]) == msg.sender,
"UUv2: Claimant is not the owner!"
);
uint256 claimAmount = calculateRewards(tokenIds[i]);
amount += claimAmount;
lastClaim[tokenIds[i]] = block.timestamp;
emit RewardsClaimed(
msg.sender,
tokenIds[i],
claimAmount,
block.timestamp
);
}
// Claim all tokens in 1 transaction
CANDY_TOKEN.mint(msg.sender, amount);
}
// --------------------- VIEW FUNCTIONS ---------------------
/// @dev Determines if UU has already been used for breeding
function canBreed(uint256 tokenId) public view returns (bool) {
return !isBred[tokenId];
}
/// @dev Get last claim timestamp of a specified tokenId
function getLastClaim(uint256 tokenId) public view returns (uint256) {
return lastClaim[tokenId];
}
/**
* @dev Get Token URI Concatenated with Base URI
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721URIStorage: URI query for nonexistent token"
);
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString()))
: "";
}
/// @dev Get ETH Mint Price. Discounts are calculated here.
function getETHPrice(address _user) public view returns (uint256) {
uint256 discount;
if (CANDY_TOKEN.balanceOf(_user) >= BREEDING_DISCOUNT_THRESHOLD[0]) {
discount = BREEDING_DISCOUNT_PERC[0];
} else if (
CANDY_TOKEN.balanceOf(_user) >= BREEDING_DISCOUNT_THRESHOLD[1]
) {
discount = BREEDING_DISCOUNT_PERC[1];
} else {
discount = 100;
}
// Take original breeding cost multiply by 90, divide by 100
return (BREEDING_COST_ETH * discount) / 100;
}
/// @dev Get UCD cost for breeding
function getUCDPrice() public view returns (uint256) {
return BREEDING_COST;
}
/// @dev Determine if breeding is open
function isBreedingOpen() public view returns (bool) {
return breedingOpen;
}
/// @dev Determine if pre-sale is open
function isPresaleOpen() public view returns (bool) {
return presaleOpen;
}
/// @dev Determine if public sale is open
function isPublicOpen() public view returns (bool) {
return publicOpen;
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerableUpgradeable, ERC721Upgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function getParents(uint256 tokenId) public view returns (Parents memory) {
return _parents[tokenId];
}
// ----------------------- CALCULATION FUNCTIONS ----------------------
/// @dev Checks if the the signature is signed by a valid signer for breeding
function breedSigned(
address sender,
bytes memory nonce,
bytes memory signature,
uint256 parent_1_id,
uint256 parent_2_id
) private view returns (bool) {
bytes32 hash = keccak256(
abi.encodePacked(sender, nonce, parent_1_id, parent_2_id)
);
return BREED_SIGNER == hash.recover(signature);
}
/// @dev Checks if the the signature is signed by a valid signer for whitelists
function whitelistSigned(
address sender,
bytes memory nonce,
bytes memory signature
) private view returns (bool) {
bytes32 hash = keccak256(abi.encodePacked(sender, nonce));
return WHITELIST_SIGNER == hash.recover(signature);
}
/// @dev Calculates the amount of UCD that can be claimed
function calculateRewards(uint256 tokenId)
public
view
returns (uint256 rewardAmount)
{
rewardAmount =
((REWARDS_PER_DAY) * (block.timestamp - getLastClaim(tokenId))) /
(1 days);
}
/** @dev Calculates the amount of UCD that can be claimed for multiple tokens
@notice Since ERC721Enumerable is not used, we must get the tokenIds owned by
the user off-chain using Moralis.
*/
function calculateRewardsMulti(uint256[] memory tokenIds)
public
view
returns (uint256 rewardAmount)
{
for (uint256 i; i < tokenIds.length; i++) {
rewardAmount += calculateRewards(tokenIds[i]);
}
}
// ---------------------- ADMIN FUNCTIONS -----------------------
/// @dev Set UCD Contract
function setCandyToken(address _addr) public onlyRole(DEFAULT_ADMIN_ROLE) {
CANDY_TOKEN = ICandyToken(_addr);
}
/// @dev Set Quantity of mints/breeds left
function setQuantity(uint256 _amount) public onlyRole(DEFAULT_ADMIN_ROLE) {
QUANTITY_LEFT = _amount;
}
/// @dev Set Rewards per day for holding UU
function setRewardsPerDay(uint256 _amount)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
REWARDS_PER_DAY = _amount;
}
/// @dev Set Breeding Cost
function setBreedingCost(uint256 _amount)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
BREEDING_COST = _amount;
}
/// @dev Set Mint Cost
function setMintCost(uint256 _amount) public onlyRole(DEFAULT_ADMIN_ROLE) {
BREEDING_COST_ETH = _amount;
}
/// @dev Update token metadata baseURI
function updateBaseURI(string memory newURI)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
_setBaseURI(newURI);
}
/// @dev Toggle Breeding Open
function toggleBreeding() public onlyRole(DEFAULT_ADMIN_ROLE) {
breedingOpen = !breedingOpen;
}
/// @dev Toggle Presale Open
function togglePresale() public onlyRole(DEFAULT_ADMIN_ROLE) {
presaleOpen = !presaleOpen;
}
/// @dev Toggle Public Open
function togglePublicSale() public onlyRole(DEFAULT_ADMIN_ROLE) {
publicOpen = !publicOpen;
}
/// @dev Pauses all token transfers.
function pause() public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
_pause();
}
/// @dev Unpauses all token transfers.
function unpause() public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
_unpause();
}
// --------------------- INTERNAL FUNCTIONS ---------------------
/// @dev Set Base URI internal function
function _setBaseURI(string memory _baseTokenURI) internal virtual {
baseTokenURI = _baseTokenURI;
}
/// @dev Gets baseToken URI
function _baseURI() internal view override returns (string memory) {
return baseTokenURI;
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721Upgradeable) whenNotPaused {
super._beforeTokenTransfer(from, to, tokenId);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ICandyToken is IERC20 {
function updateRewardOnMint(address _user, uint256 _amount) external;
function updateReward(address _from, address _to) external;
function getReward(address _to) external;
function burn(address _from, uint256 _amount) external;
function mint(address to, uint256 amount) external;
function getTotalClaimable(address _user) external view returns (uint256);
}
|
Calculates the amount of UCD that can be claimed
|
function calculateRewards(uint256 tokenId)
public
view
returns (uint256 rewardAmount)
{
rewardAmount =
((REWARDS_PER_DAY) * (block.timestamp - getLastClaim(tokenId))) /
(1 days);
}
the user off-chain using Moralis.
| 457,333 |
./full_match/97/0xA5f08a23365EFF63E2F801A945b98AFD2fEB92e6/sources/project_/contracts/piMarket.sol
|
Accepts and executes a swap. swapId The Id of the swap./
|
function acceptSwapRequest(uint256 swapId) public nonReentrant {
Swap storage swap = _swaps[swapId];
require(swap.status, "token must be on swap");
require(
ERC721(swap.requestedTokenAddress).ownerOf(swap.requestedTokenId) ==
swap.requestedTokenOwner,
"requesting token owner has changed"
);
require(
swap.requestedTokenOwner == msg.sender,
"Only requested owner can accept swap"
);
ERC721(swap.initiatorNFTAddress).safeTransferFrom(
address(this),
msg.sender,
swap.initiatorNftId
);
ERC721(swap.requestedTokenAddress).safeTransferFrom(
msg.sender,
swap.initiator,
swap.requestedTokenId
);
swap.status = false;
emit SwapAccepted(swapId);
}
| 5,040,313 |
/**
*Submitted for verification at Etherscan.io on 2021-03-15
*/
// Sources flattened with hardhat v2.1.1 https://hardhat.org
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File contracts/interfaces/IUniswapRouter.sol
pragma solidity >=0.7.0 <0.8.0;
interface IUniswapRouter {
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
}
// File contracts/interfaces/ISharer.sol
pragma solidity >=0.7.0 <0.8.0;
interface ISharer {
function distribute(address _strategy) external;
}
// File contracts/interfaces/IStrategy.sol
pragma solidity >=0.7.0 <0.8.0;
interface IStrategy {
function vault() external view returns (address);
function want() external view returns (address);
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File contracts/interfaces/Common.sol
// File contracts/interfaces/IVault.sol
pragma solidity >=0.7.0 <0.8.0;
interface IVault is IERC20 {
function withdraw() external;
}
// File contracts/StrategistProfiter.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.8.0;
pragma experimental ABIEncoderV2;
interface IWETH9 is IERC20 {
function withdraw(uint amount) external;
}
contract StrategistProfiter is Ownable {
using Address for address payable;
using SafeERC20 for IERC20;
using SafeERC20 for IVault;
struct StrategyConf {
IStrategy Strat;
IVault vault;
IERC20 want;
IERC20 sellTo;
bool sellViaSushi;
}
StrategyConf[] strategies;
address constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address constant uniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address constant sushiRouter = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F;
IWETH9 constant iWETH = IWETH9(WETH);
ISharer constant sharer = ISharer(0x2C641e14AfEcb16b4Aa6601A40EE60c3cc792f7D);
event Cloned(address payable newDeploy);
receive() external payable {}
function clone() external returns (address payable newProfiter) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(
clone_code,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone_code, 0x14), addressBytes)
mstore(
add(clone_code, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
newProfiter := create(0, clone_code, 0x37)
}
StrategistProfiter(newProfiter).transferOwnership(
msg.sender
);
emit Cloned(newProfiter);
}
function getStrategies() external view returns (StrategyConf[] memory) {
return strategies;
}
function removeStrat(uint index) external onlyOwner {
delete strategies[index];
strategies.pop();
}
function getTokenOutPath(address _token_in,address _token_out ) internal pure returns (address [] memory path) {
bool is_weth = _token_in == WETH || _token_out == WETH;
path = new address[](is_weth ? 2 : 3);
path[0] = _token_in;
if (is_weth) {
path[1] = _token_out;
} else {
path[1] = WETH;
path[2] = _token_out;
}
}
function addStrat(address strategy, address sellTo, bool useSushiToSell) external onlyOwner {
IStrategy _strat = IStrategy(strategy);
IERC20 _want = IERC20(_strat.want());
IVault _vault = IVault(_strat.vault());
strategies.push(
StrategyConf(
{
Strat: _strat,
vault: _vault,
want: _want,
sellTo: IERC20(sellTo),
sellViaSushi:useSushiToSell
}
)
);
}
function claimandSwap() external onlyOwner {
for(uint i=0;i<strategies.length;i++){
//Call dist to get the vault tokens
sharer.distribute(address(strategies[i].Strat));
//Call transfer from msg.sender
strategies[i].vault.safeTransferFrom(msg.sender, address(this), strategies[i].vault.balanceOf(msg.sender));
if(strategies[i].vault.balanceOf(address(this)) > 0) {
//Withdraw tokens to want
strategies[i].vault.withdraw();
sellToWETH(strategies[i].want,strategies[i].sellTo,strategies[i].sellViaSushi);
}
}
uint wethbal = iWETH.balanceOf(address(this));
if(wethbal > 0) iWETH.withdraw(wethbal);
msg.sender.sendValue(wethbal);
}
function sellToWETH(IERC20 _want,IERC20 _sellTo,bool _useSushi) internal {
IUniswapRouter routerTouse = _useSushi ? IUniswapRouter(sushiRouter) : IUniswapRouter(uniRouter);
uint sellAmount = _want.balanceOf(address(this));
//First approve to spend want
_want.safeApprove(address(routerTouse),sellAmount);
//Swap to sellto via path
routerTouse.swapExactTokensForTokens(sellAmount, 0, getTokenOutPath(address(_want),address(_sellTo)), address(this), block.timestamp);
}
function retrieveETH() external onlyOwner {
msg.sender.sendValue(address(this).balance);
}
function retreiveToken(address token) external onlyOwner {
IERC20 iToken = IERC20(token);
iToken.transfer(owner(),iToken.balanceOf(address(this)));
}
}
|
Call dist to get the vault tokensCall transfer from msg.senderWithdraw tokens to want
|
function claimandSwap() external onlyOwner {
for(uint i=0;i<strategies.length;i++){
sharer.distribute(address(strategies[i].Strat));
strategies[i].vault.safeTransferFrom(msg.sender, address(this), strategies[i].vault.balanceOf(msg.sender));
if(strategies[i].vault.balanceOf(address(this)) > 0) {
strategies[i].vault.withdraw();
sellToWETH(strategies[i].want,strategies[i].sellTo,strategies[i].sellViaSushi);
}
}
uint wethbal = iWETH.balanceOf(address(this));
if(wethbal > 0) iWETH.withdraw(wethbal);
msg.sender.sendValue(wethbal);
}
| 15,103,941 |
pragma solidity ^0.4.13;
contract Ownable {
address internal owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public returns (bool) {
require(newOwner != address(0x0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
return true;
}
}
contract BitNauticWhitelist is Ownable {
using SafeMath for uint256;
uint256 public usdPerEth;
constructor(uint256 _usdPerEth) public {
usdPerEth = _usdPerEth;
}
mapping(address => bool) public AMLWhitelisted;
mapping(address => uint256) public contributionCap;
/**
* @dev add an address to the whitelist
* @param addr address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function setKYCLevel(address addr, uint8 level) onlyOwner public returns (bool) {
if (level >= 3) {
contributionCap[addr] = 50000 ether; // crowdsale hard cap
} else if (level == 2) {
contributionCap[addr] = SafeMath.div(500000 * 10 ** 18, usdPerEth); // KYC Tier 2 - 500k USD
} else if (level == 1) {
contributionCap[addr] = SafeMath.div(3000 * 10 ** 18, usdPerEth); // KYC Tier 1 - 3k USD
} else {
contributionCap[addr] = 0;
}
return true;
}
/**
* @dev add addresses to the whitelist
* @param addrs addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function setKYCLevelsBulk(address[] addrs, uint8[] levels) onlyOwner external returns (bool success) {
require(addrs.length == levels.length);
for (uint256 i = 0; i < addrs.length; i++) {
assert(setKYCLevel(addrs[i], levels[i]));
}
return true;
}
function setAMLWhitelisted(address addr, bool whitelisted) onlyOwner public returns (bool) {
AMLWhitelisted[addr] = whitelisted;
return true;
}
function setAMLWhitelistedBulk(address[] addrs, bool[] whitelisted) onlyOwner external returns (bool) {
require(addrs.length == whitelisted.length);
for (uint256 i = 0; i < addrs.length; i++) {
assert(setAMLWhitelisted(addrs[i], whitelisted[i]));
}
return true;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Crowdsale is Ownable, Pausable {
using SafeMath for uint256;
// The token being sold
MintableToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public ICOStartTime;
uint256 public ICOEndTime;
// wallet address where funds will be saved
address internal wallet;
// amount of raised money in wei
uint256 public weiRaised; // internal
// Public Supply
uint256 public publicSupply;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
// BitNautic Crowdsale constructor
constructor(MintableToken _token, uint256 _publicSupply, uint256 _startTime, uint256 _endTime, address _wallet) public {
require(_endTime >= _startTime);
require(_wallet != 0x0);
// BitNautic token creation
token = _token;
// total supply of token for the crowdsale
publicSupply = _publicSupply;
// Pre-ICO start Time
ICOStartTime = _startTime;
// ICO end Time
ICOEndTime = _endTime;
// wallet where funds will be saved
wallet = _wallet;
}
// fallback function can be used to buy tokens
function() public payable {
buyTokens(msg.sender);
}
// High level token purchase function
function buyTokens(address beneficiary) whenNotPaused public payable {
require(beneficiary != 0x0);
require(validPurchase());
// minimum investment should be 0.05 ETH
uint256 lowerPurchaseLimit = 0.05 ether;
require(msg.value >= lowerPurchaseLimit);
assert(_tokenPurchased(msg.sender, beneficiary, msg.value));
// update state
weiRaised = weiRaised.add(msg.value);
forwardFunds();
}
function _tokenPurchased(address /* buyer */, address /* beneficiary */, uint256 /* weiAmount */) internal returns (bool) {
// TO BE OVERLOADED IN SUBCLASSES
return true;
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = ICOStartTime <= now && now <= ICOEndTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
return now > ICOEndTime;
}
bool public checkBurnTokens = false;
function burnTokens() onlyOwner public returns (bool) {
require(hasEnded());
require(!checkBurnTokens);
token.mint(0x0, publicSupply);
token.burnTokens(publicSupply);
publicSupply = 0;
checkBurnTokens = true;
return true;
}
function getTokenAddress() onlyOwner public view returns (address) {
return address(token);
}
}
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 internal cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
// overriding Crowdsale#validPurchase to add extra cap logic
// @return true if investors can buy at the moment
function validPurchase() internal constant returns (bool) {
bool withinCap = weiRaised.add(msg.value) <= cap;
return super.validPurchase() && withinCap;
}
// overriding Crowdsale#hasEnded to add cap logic
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
bool capReached = weiRaised >= cap;
return super.hasEnded() || capReached;
}
}
contract FinalizableCrowdsale is Crowdsale {
using SafeMath for uint256;
bool isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalizeCrowdsale() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
emit Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
contract RefundVault is Ownable {
using SafeMath for uint256;
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
address public wallet;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
constructor(address _wallet) public {
require(_wallet != 0x0);
wallet = _wallet;
state = State.Active;
}
function deposit(address investor) onlyOwner public payable {
require(state == State.Active);
deposited[investor] = deposited[investor].add(msg.value);
}
function close() onlyOwner public {
require(state == State.Active);
state = State.Closed;
emit Closed();
wallet.transfer(address(this).balance);
}
function enableRefunds() onlyOwner public {
require(state == State.Active);
state = State.Refunding;
emit RefundsEnabled();
}
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
emit Refunded(investor, depositedValue);
}
}
contract RefundableCrowdsale is FinalizableCrowdsale {
using SafeMath for uint256;
// minimum amount of funds to be raised in weis
uint256 internal goal;
bool internal _goalReached = false;
// refund vault used to hold funds while crowdsale is running
RefundVault private vault;
constructor(uint256 _goal) public {
require(_goal > 0);
vault = new RefundVault(wallet);
goal = _goal;
}
// We're overriding the fund forwarding from Crowdsale.
// In addition to sending the funds, we want to call
// the RefundVault deposit function
function forwardFunds() internal {
vault.deposit.value(msg.value)(msg.sender);
}
// if crowdsale is unsuccessful, investors can claim refunds here
function claimRefund() public {
require(isFinalized);
require(!goalReached());
vault.refund(msg.sender);
}
// vault finalization task, called when owner calls finalize()
function finalization() internal {
if (goalReached()) {
vault.close();
} else {
vault.enableRefunds();
}
super.finalization();
}
function goalReached() public returns (bool) {
if (weiRaised >= goal) {
_goalReached = true;
}
return _goalReached;
}
// function updateGoalCheck() onlyOwner public {
// _goalReached = true;
// }
function getVaultAddress() onlyOwner public view returns (address) {
return vault;
}
}
contract BitNauticCrowdsale is CappedCrowdsale, RefundableCrowdsale {
uint256 constant public crowdsaleInitialSupply = 35000000 * 10 ** 18; // 70% of token cap
// uint256 constant public crowdsaleSoftCap = 2 ether;
// uint256 constant public crowdsaleHardCap = 10 ether;
uint256 constant public crowdsaleSoftCap = 5000 ether;
uint256 constant public crowdsaleHardCap = 50000 ether;
uint256 constant public preICOStartTime = 1525132800; // 2018-05-01 00:00 GMT+0
uint256 constant public mainICOStartTime = 1527811200; // 2018-06-01 00:00 GMT+0
uint256 constant public mainICOFirstWeekEndTime = 1528416000; // 2018-06-08 00:00 GMT+0
uint256 constant public mainICOSecondWeekEndTime = 1529020800; // 2018-06-15 00:00 GMT+0
uint256 constant public mainICOThirdWeekEndTime = 1529625600; // 2018-06-22 00:00 GMT+0
uint256 constant public mainICOFourthWeekEndTime = 1530403200; // 2018-07-01 00:00 GMT+0
uint256 constant public mainICOEndTime = 1532995200; // 2018-07-31 00:00 GMT+0
// uint256 public preICOStartTime = now; // 2018-05-01 00:00 GMT+0
// uint256 constant public mainICOStartTime = preICOStartTime; // 2018-06-01 00:00 GMT+0
// uint256 constant public mainICOFirstWeekEndTime = mainICOStartTime; // 2018-06-08 00:00 GMT+0
// uint256 constant public mainICOSecondWeekEndTime = mainICOFirstWeekEndTime; // 2018-06-15 00:00 GMT+0
// uint256 constant public mainICOThirdWeekEndTime = mainICOSecondWeekEndTime; // 2018-06-22 00:00 GMT+0
// uint256 constant public mainICOFourthWeekEndTime = mainICOThirdWeekEndTime; // 2018-07-01 00:00 GMT+0
// uint256 constant public mainICOEndTime = mainICOFourthWeekEndTime + 5 minutes; // 2018-07-30 00:00 GMT+0
uint256 constant public tokenBaseRate = 500; // 1 ETH = 500 BTNT
// bonuses in percentage
uint256 constant public preICOBonus = 30;
uint256 constant public firstWeekBonus = 20;
uint256 constant public secondWeekBonus = 15;
uint256 constant public thirdWeekBonus = 10;
uint256 constant public fourthWeekBonus = 5;
uint256 public teamSupply = 3000000 * 10 ** 18; // 6% of token cap
uint256 public bountySupply = 2500000 * 10 ** 18; // 5% of token cap
uint256 public reserveSupply = 5000000 * 10 ** 18; // 10% of token cap
uint256 public advisorSupply = 2500000 * 10 ** 18; // 5% of token cap
uint256 public founderSupply = 2000000 * 10 ** 18; // 4% of token cap
// amount of tokens each address will receive at the end of the crowdsale
mapping (address => uint256) public creditOf;
mapping (address => uint256) public weiInvestedBy;
BitNauticWhitelist public whitelist;
/** Constructor BitNauticICO */
constructor(BitNauticToken _token, BitNauticWhitelist _whitelist, address _wallet)
CappedCrowdsale(crowdsaleHardCap)
FinalizableCrowdsale()
RefundableCrowdsale(crowdsaleSoftCap)
Crowdsale(_token, crowdsaleInitialSupply, preICOStartTime, mainICOEndTime, _wallet) public
{
whitelist = _whitelist;
}
function _tokenPurchased(address buyer, address beneficiary, uint256 weiAmount) internal returns (bool) {
require(SafeMath.add(weiInvestedBy[buyer], weiAmount) <= whitelist.contributionCap(buyer));
uint256 tokens = SafeMath.mul(weiAmount, tokenBaseRate);
tokens = tokens.add(SafeMath.mul(tokens, getCurrentBonus()).div(100));
require(publicSupply >= tokens);
publicSupply = publicSupply.sub(tokens);
creditOf[beneficiary] = creditOf[beneficiary].add(tokens);
weiInvestedBy[buyer] = SafeMath.add(weiInvestedBy[buyer], weiAmount);
emit TokenPurchase(buyer, beneficiary, weiAmount, tokens);
return true;
}
address constant public privateSaleWallet = 0x5A01D561AE864006c6B733f21f8D4311d1E1B42a;
function goalReached() public returns (bool) {
if (weiRaised + privateSaleWallet.balance >= goal) {
_goalReached = true;
}
return _goalReached;
}
function getCurrentBonus() public view returns (uint256) {
if (now < mainICOStartTime) {
return preICOBonus;
} else if (now < mainICOFirstWeekEndTime) {
return firstWeekBonus;
} else if (now < mainICOSecondWeekEndTime) {
return secondWeekBonus;
} else if (now < mainICOThirdWeekEndTime) {
return thirdWeekBonus;
} else if (now < mainICOFourthWeekEndTime) {
return fourthWeekBonus;
} else {
return 0;
}
}
function claimBitNauticTokens() public returns (bool) {
return grantInvestorTokens(msg.sender);
}
function grantInvestorTokens(address investor) public returns (bool) {
require(creditOf[investor] > 0);
require(now > mainICOEndTime && whitelist.AMLWhitelisted(investor));
require(goalReached());
assert(token.mint(investor, creditOf[investor]));
creditOf[investor] = 0;
return true;
}
function grantInvestorsTokens(address[] investors) public returns (bool) {
require(now > mainICOEndTime);
require(goalReached());
for (uint256 i = 0; i < investors.length; i++) {
if (creditOf[investors[i]] > 0 && whitelist.AMLWhitelisted(investors[i])) {
token.mint(investors[i], creditOf[investors[i]]);
creditOf[investors[i]] = 0;
}
}
return true;
}
function bountyDrop(address[] recipients, uint256[] values) onlyOwner public returns (bool) {
require(now > mainICOEndTime);
require(goalReached());
require(recipients.length == values.length);
for (uint256 i = 0; i < recipients.length; i++) {
values[i] = SafeMath.mul(values[i], 1 ether);
if (bountySupply >= values[i]) {
return false;
}
bountySupply = SafeMath.sub(bountySupply, values[i]);
token.mint(recipients[i], values[i]);
}
return true;
}
uint256 public teamTimeLock = mainICOEndTime;
uint256 public founderTimeLock = mainICOEndTime + 365 days;
uint256 public advisorTimeLock = mainICOEndTime + 180 days;
uint256 public reserveTimeLock = mainICOEndTime;
function grantAdvisorTokens(address advisorAddress) onlyOwner public {
require((advisorSupply > 0) && (advisorTimeLock < now));
require(goalReached());
token.mint(advisorAddress, advisorSupply);
advisorSupply = 0;
}
uint256 public teamVestingCounter = 0; // months of vesting
function grantTeamTokens(address teamAddress) onlyOwner public {
require((teamVestingCounter < 12) && (teamTimeLock < now));
require(goalReached());
teamTimeLock = SafeMath.add(teamTimeLock, 4 weeks);
token.mint(teamAddress, SafeMath.div(teamSupply, 12));
teamVestingCounter = SafeMath.add(teamVestingCounter, 1);
}
function grantFounderTokens(address founderAddress) onlyOwner public {
require((founderSupply > 0) && (founderTimeLock < now));
require(goalReached());
token.mint(founderAddress, founderSupply);
founderSupply = 0;
}
function grantReserveTokens(address beneficiary) onlyOwner public {
require((reserveSupply > 0) && (now > reserveTimeLock));
require(goalReached());
token.mint(beneficiary, reserveSupply);
reserveSupply = 0;
}
function transferTokenOwnership(address newTokenOwner) onlyOwner public returns (bool) {
return token.transferOwnership(newTokenOwner);
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = SafeMath.add(totalSupply, _amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(0x0, _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
// function finishMinting() onlyOwner public returns (bool) {
// mintingFinished = true;
// emit MintFinished();
// return true;
// }
function burnTokens(uint256 _unsoldTokens) onlyOwner canMint public returns (bool) {
totalSupply = SafeMath.sub(totalSupply, _unsoldTokens);
}
}
contract CappedToken is MintableToken {
uint256 public cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(totalSupply.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
contract BitNauticToken is CappedToken {
string public constant name = "BitNautic Token";
string public constant symbol = "BTNT";
uint8 public constant decimals = 18;
uint256 public totalSupply = 0;
constructor()
CappedToken(50000000 * 10 ** uint256(decimals)) public
{
}
}
|
High level token purchase function minimum investment should be 0.05 ETH update state
|
function buyTokens(address beneficiary) whenNotPaused public payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 lowerPurchaseLimit = 0.05 ether;
require(msg.value >= lowerPurchaseLimit);
assert(_tokenPurchased(msg.sender, beneficiary, msg.value));
weiRaised = weiRaised.add(msg.value);
forwardFunds();
}
| 6,476,941 |
pragma solidity ^0.5.2;
library SafeMath {
function MUL925(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b);
return c;
}
function DIV533(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
require(b > 0);
uint c = a / b;
return c;
}
function SUB977(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
require(b <= a);
uint c = a - b;
return c;
}
function ADD680(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
uint c = a + b;
require(c >= a);
return c;
}
}
contract Token {
function TOTALSUPPLY944() public returns (uint supply) {} //inject NONSTANDARD NAMING
function BALANCEOF651(address _owner) public returns (uint balance) {} //inject NONSTANDARD NAMING
function TRANSFER915(address _to, uint _value) public returns (bool success) {} //inject NONSTANDARD NAMING
function TRANSFERFROM250(address _from, address _to, uint _value) public returns (bool success) {} //inject NONSTANDARD NAMING
function APPROVE235(address _spender, uint _value) public returns (bool success) {} //inject NONSTANDARD NAMING
function ALLOWANCE981(address _owner, address _spender) public returns (uint remaining) {} //inject NONSTANDARD NAMING
event TRANSFER161(address indexed _from, address indexed _to, uint _value); //inject NONSTANDARD NAMING
event APPROVAL494(address indexed _owner, address indexed _spender, uint _value); //inject NONSTANDARD NAMING
uint public decimals;
string public name;
string public symbol;
}
contract DEX_Orgon {
using SafeMath for uint;
address public admin; //the admin address
address public feeAccount; //the account that will receive fees
mapping (address => uint) public feeMake; //percentage times (1 ether) (sell fee)
mapping (address => uint) public feeTake; //percentage times (1 ether) (buy fee)
mapping (address => uint) public feeDeposit; //percentage times (1 ether)
mapping (address => uint) public feeWithdraw; //percentage times (1 ether)
mapping (address => mapping (address => uint)) public tokens; //mapping of token addresses to mapping of account balances (token=0 means Ether)
mapping (address => mapping (bytes32 => bool)) public orders; //mapping of user accounts to mapping of order hashes to booleans (true = submitted by user, equivalent to offchain signature)
mapping (address => mapping (bytes32 => uint)) public orderFills; //mapping of user accounts to mapping of order hashes to uints (amount of order that has been filled)
mapping (address => bool) public activeTokens;
mapping (address => uint) public tokensMinAmountBuy;
mapping (address => uint) public tokensMinAmountSell;
event ORDER901(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user); //inject NONSTANDARD NAMING
event CANCEL650(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s); //inject NONSTANDARD NAMING
event TRADE560(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give); //inject NONSTANDARD NAMING
event DEPOSIT211(address token, address user, uint amount, uint balance); //inject NONSTANDARD NAMING
event WITHDRAW585(address token, address user, uint amount, uint balance); //inject NONSTANDARD NAMING
event ACTIVATETOKEN153(address token, string symbol); //inject NONSTANDARD NAMING
event DEACTIVATETOKEN237(address token, string symbol); //inject NONSTANDARD NAMING
constructor (address admin_, address feeAccount_) public {
admin = admin_;
feeAccount = feeAccount_;
}
function CHANGEADMIN303(address admin_) public { //inject NONSTANDARD NAMING
require (msg.sender == admin);
admin = admin_;
}
function CHANGEFEEACCOUNT535(address feeAccount_) public { //inject NONSTANDARD NAMING
require (msg.sender == admin);
feeAccount = feeAccount_;
}
function DEPOSIT962() public payable { //inject NONSTANDARD NAMING
uint feeDepositXfer = msg.value.MUL925(feeDeposit[address(0)]) / (1 ether);
uint depositAmount = msg.value.SUB977(feeDepositXfer);
tokens[address(0)][msg.sender] = tokens[address(0)][msg.sender].ADD680(depositAmount);
tokens[address(0)][feeAccount] = tokens[address(0)][feeAccount].ADD680(feeDepositXfer);
emit DEPOSIT211(address(0), msg.sender, msg.value, tokens[address(0)][msg.sender]);
}
function WITHDRAW601(uint amount) public { //inject NONSTANDARD NAMING
require (tokens[address(0)][msg.sender] >= amount);
uint feeWithdrawXfer = amount.MUL925(feeWithdraw[address(0)]) / (1 ether);
uint withdrawAmount = amount.SUB977(feeWithdrawXfer);
tokens[address(0)][msg.sender] = tokens[address(0)][msg.sender].SUB977(amount);
tokens[address(0)][feeAccount] = tokens[address(0)][feeAccount].ADD680(feeWithdrawXfer);
msg.sender.transfer(withdrawAmount);
emit WITHDRAW585(address(0), msg.sender, amount, tokens[address(0)][msg.sender]);
}
function DEPOSITTOKEN735(address token, uint amount) public { //inject NONSTANDARD NAMING
require (token != address(0));
require (ISTOKENACTIVE523(token));
require(Token(token).TRANSFERFROM250(msg.sender, address(this), amount));
uint feeDepositXfer = amount.MUL925(feeDeposit[token]) / (1 ether);
uint depositAmount = amount.SUB977(feeDepositXfer);
tokens[token][msg.sender] = tokens[token][msg.sender].ADD680(depositAmount);
tokens[token][feeAccount] = tokens[token][feeAccount].ADD680(feeDepositXfer);
emit DEPOSIT211(token, msg.sender, amount, tokens[token][msg.sender]);
}
function WITHDRAWTOKEN844(address token, uint amount) public { //inject NONSTANDARD NAMING
require (token != address(0));
require (tokens[token][msg.sender] >= amount);
uint feeWithdrawXfer = amount.MUL925(feeWithdraw[token]) / (1 ether);
uint withdrawAmount = amount.SUB977(feeWithdrawXfer);
tokens[token][msg.sender] = tokens[token][msg.sender].SUB977(amount);
tokens[token][feeAccount] = tokens[token][feeAccount].ADD680(feeWithdrawXfer);
require (Token(token).TRANSFER915(msg.sender, withdrawAmount));
emit WITHDRAW585(token, msg.sender, amount, tokens[token][msg.sender]);
}
function BALANCEOF651(address token, address user) view public returns (uint) { //inject NONSTANDARD NAMING
return tokens[token][user];
}
function ORDER93(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce) public { //inject NONSTANDARD NAMING
require (ISTOKENACTIVE523(tokenGet) && ISTOKENACTIVE523(tokenGive));
require (amountGet >= tokensMinAmountBuy[tokenGet]) ;
require (amountGive >= tokensMinAmountSell[tokenGive]) ;
bytes32 hash = sha256(abi.encodePacked(address(this), tokenGet, amountGet, tokenGive, amountGive, expires, nonce));
orders[msg.sender][hash] = true;
emit ORDER901(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender);
}
function TRADE298(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) public { //inject NONSTANDARD NAMING
require (ISTOKENACTIVE523(tokenGet) && ISTOKENACTIVE523(tokenGive));
//amount is in amountGet terms
bytes32 hash = sha256(abi.encodePacked(address(this), tokenGet, amountGet, tokenGive, amountGive, expires, nonce));
require (
(orders[user][hash] || ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)),v,r,s) == user) &&
block.number <= expires &&
orderFills[user][hash].ADD680(amount) <= amountGet
);
TRADEBALANCES341(tokenGet, amountGet, tokenGive, amountGive, user, amount);
orderFills[user][hash] = orderFills[user][hash].ADD680(amount);
emit TRADE560(tokenGet, amount, tokenGive, amountGive * amount / amountGet, user, msg.sender);
}
function TRADEBALANCES341(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private { //inject NONSTANDARD NAMING
uint feeMakeXfer = amount.MUL925(feeMake[tokenGet]) / (1 ether);
uint feeTakeXfer = amount.MUL925(feeTake[tokenGet]) / (1 ether);
tokens[tokenGet][msg.sender] = tokens[tokenGet][msg.sender].SUB977(amount.ADD680(feeTakeXfer));
tokens[tokenGet][user] = tokens[tokenGet][user].ADD680(amount.SUB977(feeMakeXfer));
tokens[tokenGet][feeAccount] = tokens[tokenGet][feeAccount].ADD680(feeMakeXfer.ADD680(feeTakeXfer));
tokens[tokenGive][user] = tokens[tokenGive][user].SUB977(amountGive.MUL925(amount).DIV533(amountGet));
tokens[tokenGive][msg.sender] = tokens[tokenGive][msg.sender].ADD680(amountGive.MUL925(amount).DIV533(amountGet));
}
function TESTTRADE501(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) view public returns(bool) { //inject NONSTANDARD NAMING
if (!ISTOKENACTIVE523(tokenGet) || !ISTOKENACTIVE523(tokenGive)) return false;
if (!(
tokens[tokenGet][sender] >= amount &&
AVAILABLEVOLUME148(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) >= amount
)) return false;
return true;
}
function AVAILABLEVOLUME148(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) view public returns(uint) { //inject NONSTANDARD NAMING
bytes32 hash = sha256(abi.encodePacked(address(this), tokenGet, amountGet, tokenGive, amountGive, expires, nonce));
if (!(
(orders[user][hash] || ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)),v,r,s) == user) &&
block.number <= expires
)) return 0;
return AVAILABLE249(amountGet, tokenGive, amountGive, user, hash);
}
function AVAILABLE249(uint amountGet, address tokenGive, uint amountGive, address user, bytes32 hash) view private returns(uint) { //inject NONSTANDARD NAMING
uint available1 = AVAILABLE1164(user, amountGet, hash);
uint available2 = AVAILABLE265(user, tokenGive, amountGet, amountGive);
if (available1 < available2) return available1;
return available2;
}
function AVAILABLE1164(address user, uint amountGet, bytes32 orderHash) view private returns(uint) { //inject NONSTANDARD NAMING
return amountGet.SUB977(orderFills[user][orderHash]);
}
function AVAILABLE265(address user, address tokenGive, uint amountGet, uint amountGive) view private returns(uint) { //inject NONSTANDARD NAMING
return tokens[tokenGive][user].MUL925(amountGet).DIV533(amountGive);
}
function AMOUNTFILLED138(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user) view public returns(uint) { //inject NONSTANDARD NAMING
bytes32 hash = sha256(abi.encodePacked(address(this), tokenGet, amountGet, tokenGive, amountGive, expires, nonce));
return orderFills[user][hash];
}
function CANCELORDER664(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, uint8 v, bytes32 r, bytes32 s) public { //inject NONSTANDARD NAMING
bytes32 hash = sha256(abi.encodePacked(address(this), tokenGet, amountGet, tokenGive, amountGive, expires, nonce));
require (orders[msg.sender][hash] || ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)),v,r,s) == msg.sender);
orderFills[msg.sender][hash] = amountGet;
emit CANCEL650(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender, v, r, s);
}
function ACTIVATETOKEN73(address token) public { //inject NONSTANDARD NAMING
require (msg.sender == admin);
activeTokens[token] = true;
emit ACTIVATETOKEN153(token, Token(token).symbol());
}
function DEACTIVATETOKEN190(address token) public { //inject NONSTANDARD NAMING
require (msg.sender == admin);
activeTokens[token] = false;
emit DEACTIVATETOKEN237(token, Token(token).symbol());
}
function ISTOKENACTIVE523(address token) view public returns(bool) { //inject NONSTANDARD NAMING
if (token == address(0))
return true; // eth is always active
return activeTokens[token];
}
function SETTOKENMINAMOUNTBUY334(address token, uint amount) public { //inject NONSTANDARD NAMING
require (msg.sender == admin);
tokensMinAmountBuy[token] = amount;
}
function SETTOKENMINAMOUNTSELL817(address token, uint amount) public { //inject NONSTANDARD NAMING
require (msg.sender == admin);
tokensMinAmountSell[token] = amount;
}
function SETTOKENFEEMAKE257(address token, uint feeMake_) public { //inject NONSTANDARD NAMING
require (msg.sender == admin);
feeMake[token] = feeMake_;
}
function SETTOKENFEETAKE459(address token, uint feeTake_) public { //inject NONSTANDARD NAMING
require (msg.sender == admin);
feeTake[token] = feeTake_;
}
function SETTOKENFEEDEPOSIT880(address token, uint feeDeposit_) public { //inject NONSTANDARD NAMING
require (msg.sender == admin);
feeDeposit[token] = feeDeposit_;
}
function SETTOKENFEEWITHDRAW248(address token, uint feeWithdraw_) public { //inject NONSTANDARD NAMING
require (msg.sender == admin);
feeWithdraw[token] = feeWithdraw_;
}
}
|
inject NONSTANDARD NAMING
|
function AVAILABLE265(address user, address tokenGive, uint amountGet, uint amountGive) view private returns(uint) {
| 5,497,587 |
//SPDX-License-Identifier: Unlicense
pragma solidity 0.6.11;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract AirdropPush {
using SafeERC20 for IERC20;
function distribute(
IERC20 token,
address[] calldata accounts,
uint256[] calldata amounts
) external {
require(accounts.length == amounts.length, "LENGTH_MISMATCH");
for (uint256 i = 0; i < accounts.length; i++) {
token.safeTransferFrom(msg.sender, accounts[i], amounts[i]);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@0x/contracts-zero-ex/contracts/src/features/interfaces/INativeOrdersFeature.sol";
import "../interfaces/IWallet.sol";
contract ZeroExTradeWallet is IWallet, Ownable {
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
INativeOrdersFeature public zeroExRouter;
address public manager;
EnumerableSet.AddressSet internal tokens;
modifier onlyManager() {
require(msg.sender == manager, "INVALID_MANAGER");
_;
}
constructor(address newRouter, address newManager) public {
require(newRouter != address(0), "INVALID_ROUTER");
require(newManager != address(0), "INVALID_MANAGER");
zeroExRouter = INativeOrdersFeature(newRouter);
manager = newManager;
}
function getTokens() external view returns (address[] memory) {
address[] memory returnData = new address[](tokens.length());
for (uint256 i = 0; i < tokens.length(); i++) {
returnData[i] = tokens.at(i);
}
return returnData;
}
// solhint-disable-next-line no-empty-blocks
function registerAllowedOrderSigner(address signer, bool allowed) external override onlyOwner {
require(signer != address(0), "INVALID_SIGNER");
zeroExRouter.registerAllowedOrderSigner(signer, allowed);
}
function deposit(address[] calldata tokensToAdd, uint256[] calldata amounts)
external
override
onlyManager
{
uint256 tokensLength = tokensToAdd.length;
uint256 amountsLength = amounts.length;
require(tokensLength > 0, "EMPTY_TOKEN_LIST");
require(tokensLength == amountsLength, "LENGTH_MISMATCH");
for (uint256 i = 0; i < tokensLength; i++) {
IERC20(tokensToAdd[i]).safeTransferFrom(msg.sender, address(this), amounts[i]);
// NOTE: approval must be done after transferFrom; balance is checked in the approval
_approve(IERC20(tokensToAdd[i]));
tokens.add(address(tokensToAdd[i]));
}
}
function withdraw(address[] calldata tokensToWithdraw, uint256[] calldata amounts)
external
override
onlyManager
{
uint256 tokensLength = tokensToWithdraw.length;
uint256 amountsLength = amounts.length;
require(tokensLength > 0, "EMPTY_TOKEN_LIST");
require(tokensLength == amountsLength, "LENGTH_MISMATCH");
for (uint256 i = 0; i < tokensLength; i++) {
IERC20(tokensToWithdraw[i]).safeTransfer(msg.sender, amounts[i]);
if (IERC20(tokensToWithdraw[i]).balanceOf(address(this)) == 0) {
tokens.remove(address(tokensToWithdraw[i]));
}
}
}
function _approve(IERC20 token) internal {
// Approve the zeroExRouter's allowance to max if the allowance ever drops below the balance of the token held
uint256 allowance = token.allowance(address(this), address(zeroExRouter));
if (allowance < token.balanceOf(address(this))) {
if (allowance != 0) {
token.safeApprove(address(zeroExRouter), 0);
}
token.safeApprove(address(zeroExRouter), type(uint256).max);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "../libs/LibSignature.sol";
import "../libs/LibNativeOrder.sol";
import "./INativeOrdersEvents.sol";
/// @dev Feature for interacting with limit orders.
interface INativeOrdersFeature is
INativeOrdersEvents
{
/// @dev Transfers protocol fees from the `FeeCollector` pools into
/// the staking contract.
/// @param poolIds Staking pool IDs
function transferProtocolFeesForPools(bytes32[] calldata poolIds)
external;
/// @dev Fill a limit order. The taker and sender will be the caller.
/// @param order The limit order. ETH protocol fees can be
/// attached to this call. Any unspent ETH will be refunded to
/// the caller.
/// @param signature The order signature.
/// @param takerTokenFillAmount Maximum taker token amount to fill this order with.
/// @return takerTokenFilledAmount How much maker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillLimitOrder(
LibNativeOrder.LimitOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
)
external
payable
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Fill an RFQ order for up to `takerTokenFillAmount` taker tokens.
/// The taker will be the caller.
/// @param order The RFQ order.
/// @param signature The order signature.
/// @param takerTokenFillAmount Maximum taker token amount to fill this order with.
/// @return takerTokenFilledAmount How much maker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillRfqOrder(
LibNativeOrder.RfqOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
)
external
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Fill an RFQ order for exactly `takerTokenFillAmount` taker tokens.
/// The taker will be the caller. ETH protocol fees can be
/// attached to this call. Any unspent ETH will be refunded to
/// the caller.
/// @param order The limit order.
/// @param signature The order signature.
/// @param takerTokenFillAmount How much taker token to fill this order with.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillOrKillLimitOrder(
LibNativeOrder.LimitOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
)
external
payable
returns (uint128 makerTokenFilledAmount);
/// @dev Fill an RFQ order for exactly `takerTokenFillAmount` taker tokens.
/// The taker will be the caller.
/// @param order The RFQ order.
/// @param signature The order signature.
/// @param takerTokenFillAmount How much taker token to fill this order with.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillOrKillRfqOrder(
LibNativeOrder.RfqOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
)
external
returns (uint128 makerTokenFilledAmount);
/// @dev Fill a limit order. Internal variant. ETH protocol fees can be
/// attached to this call. Any unspent ETH will be refunded to
/// `msg.sender` (not `sender`).
/// @param order The limit order.
/// @param signature The order signature.
/// @param takerTokenFillAmount Maximum taker token to fill this order with.
/// @param taker The order taker.
/// @param sender The order sender.
/// @return takerTokenFilledAmount How much maker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function _fillLimitOrder(
LibNativeOrder.LimitOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount,
address taker,
address sender
)
external
payable
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Fill an RFQ order. Internal variant.
/// @param order The RFQ order.
/// @param signature The order signature.
/// @param takerTokenFillAmount Maximum taker token to fill this order with.
/// @param taker The order taker.
/// @return takerTokenFilledAmount How much maker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function _fillRfqOrder(
LibNativeOrder.RfqOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount,
address taker
)
external
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Cancel a single limit order. The caller must be the maker or a valid order signer.
/// Silently succeeds if the order has already been cancelled.
/// @param order The limit order.
function cancelLimitOrder(LibNativeOrder.LimitOrder calldata order)
external;
/// @dev Cancel a single RFQ order. The caller must be the maker or a valid order signer.
/// Silently succeeds if the order has already been cancelled.
/// @param order The RFQ order.
function cancelRfqOrder(LibNativeOrder.RfqOrder calldata order)
external;
/// @dev Mark what tx.origin addresses are allowed to fill an order that
/// specifies the message sender as its txOrigin.
/// @param origins An array of origin addresses to update.
/// @param allowed True to register, false to unregister.
function registerAllowedRfqOrigins(address[] memory origins, bool allowed)
external;
/// @dev Cancel multiple limit orders. The caller must be the maker or a valid order signer.
/// Silently succeeds if the order has already been cancelled.
/// @param orders The limit orders.
function batchCancelLimitOrders(LibNativeOrder.LimitOrder[] calldata orders)
external;
/// @dev Cancel multiple RFQ orders. The caller must be the maker or a valid order signer.
/// Silently succeeds if the order has already been cancelled.
/// @param orders The RFQ orders.
function batchCancelRfqOrders(LibNativeOrder.RfqOrder[] calldata orders)
external;
/// @dev Cancel all limit orders for a given maker and pair with a salt less
/// than the value provided. The caller must be the maker. Subsequent
/// calls to this function with the same caller and pair require the
/// new salt to be >= the old salt.
/// @param makerToken The maker token.
/// @param takerToken The taker token.
/// @param minValidSalt The new minimum valid salt.
function cancelPairLimitOrders(
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
)
external;
/// @dev Cancel all limit orders for a given maker and pair with a salt less
/// than the value provided. The caller must be a signer registered to the maker.
/// Subsequent calls to this function with the same maker and pair require the
/// new salt to be >= the old salt.
/// @param maker The maker for which to cancel.
/// @param makerToken The maker token.
/// @param takerToken The taker token.
/// @param minValidSalt The new minimum valid salt.
function cancelPairLimitOrdersWithSigner(
address maker,
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
)
external;
/// @dev Cancel all limit orders for a given maker and pairs with salts less
/// than the values provided. The caller must be the maker. Subsequent
/// calls to this function with the same caller and pair require the
/// new salt to be >= the old salt.
/// @param makerTokens The maker tokens.
/// @param takerTokens The taker tokens.
/// @param minValidSalts The new minimum valid salts.
function batchCancelPairLimitOrders(
IERC20TokenV06[] calldata makerTokens,
IERC20TokenV06[] calldata takerTokens,
uint256[] calldata minValidSalts
)
external;
/// @dev Cancel all limit orders for a given maker and pairs with salts less
/// than the values provided. The caller must be a signer registered to the maker.
/// Subsequent calls to this function with the same maker and pair require the
/// new salt to be >= the old salt.
/// @param maker The maker for which to cancel.
/// @param makerTokens The maker tokens.
/// @param takerTokens The taker tokens.
/// @param minValidSalts The new minimum valid salts.
function batchCancelPairLimitOrdersWithSigner(
address maker,
IERC20TokenV06[] memory makerTokens,
IERC20TokenV06[] memory takerTokens,
uint256[] memory minValidSalts
)
external;
/// @dev Cancel all RFQ orders for a given maker and pair with a salt less
/// than the value provided. The caller must be the maker. Subsequent
/// calls to this function with the same caller and pair require the
/// new salt to be >= the old salt.
/// @param makerToken The maker token.
/// @param takerToken The taker token.
/// @param minValidSalt The new minimum valid salt.
function cancelPairRfqOrders(
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
)
external;
/// @dev Cancel all RFQ orders for a given maker and pair with a salt less
/// than the value provided. The caller must be a signer registered to the maker.
/// Subsequent calls to this function with the same maker and pair require the
/// new salt to be >= the old salt.
/// @param maker The maker for which to cancel.
/// @param makerToken The maker token.
/// @param takerToken The taker token.
/// @param minValidSalt The new minimum valid salt.
function cancelPairRfqOrdersWithSigner(
address maker,
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
)
external;
/// @dev Cancel all RFQ orders for a given maker and pairs with salts less
/// than the values provided. The caller must be the maker. Subsequent
/// calls to this function with the same caller and pair require the
/// new salt to be >= the old salt.
/// @param makerTokens The maker tokens.
/// @param takerTokens The taker tokens.
/// @param minValidSalts The new minimum valid salts.
function batchCancelPairRfqOrders(
IERC20TokenV06[] calldata makerTokens,
IERC20TokenV06[] calldata takerTokens,
uint256[] calldata minValidSalts
)
external;
/// @dev Cancel all RFQ orders for a given maker and pairs with salts less
/// than the values provided. The caller must be a signer registered to the maker.
/// Subsequent calls to this function with the same maker and pair require the
/// new salt to be >= the old salt.
/// @param maker The maker for which to cancel.
/// @param makerTokens The maker tokens.
/// @param takerTokens The taker tokens.
/// @param minValidSalts The new minimum valid salts.
function batchCancelPairRfqOrdersWithSigner(
address maker,
IERC20TokenV06[] memory makerTokens,
IERC20TokenV06[] memory takerTokens,
uint256[] memory minValidSalts
)
external;
/// @dev Get the order info for a limit order.
/// @param order The limit order.
/// @return orderInfo Info about the order.
function getLimitOrderInfo(LibNativeOrder.LimitOrder calldata order)
external
view
returns (LibNativeOrder.OrderInfo memory orderInfo);
/// @dev Get the order info for an RFQ order.
/// @param order The RFQ order.
/// @return orderInfo Info about the order.
function getRfqOrderInfo(LibNativeOrder.RfqOrder calldata order)
external
view
returns (LibNativeOrder.OrderInfo memory orderInfo);
/// @dev Get the canonical hash of a limit order.
/// @param order The limit order.
/// @return orderHash The order hash.
function getLimitOrderHash(LibNativeOrder.LimitOrder calldata order)
external
view
returns (bytes32 orderHash);
/// @dev Get the canonical hash of an RFQ order.
/// @param order The RFQ order.
/// @return orderHash The order hash.
function getRfqOrderHash(LibNativeOrder.RfqOrder calldata order)
external
view
returns (bytes32 orderHash);
/// @dev Get the protocol fee multiplier. This should be multiplied by the
/// gas price to arrive at the required protocol fee to fill a native order.
/// @return multiplier The protocol fee multiplier.
function getProtocolFeeMultiplier()
external
view
returns (uint32 multiplier);
/// @dev Get order info, fillable amount, and signature validity for a limit order.
/// Fillable amount is determined using balances and allowances of the maker.
/// @param order The limit order.
/// @param signature The order signature.
/// @return orderInfo Info about the order.
/// @return actualFillableTakerTokenAmount How much of the order is fillable
/// based on maker funds, in taker tokens.
/// @return isSignatureValid Whether the signature is valid.
function getLimitOrderRelevantState(
LibNativeOrder.LimitOrder calldata order,
LibSignature.Signature calldata signature
)
external
view
returns (
LibNativeOrder.OrderInfo memory orderInfo,
uint128 actualFillableTakerTokenAmount,
bool isSignatureValid
);
/// @dev Get order info, fillable amount, and signature validity for an RFQ order.
/// Fillable amount is determined using balances and allowances of the maker.
/// @param order The RFQ order.
/// @param signature The order signature.
/// @return orderInfo Info about the order.
/// @return actualFillableTakerTokenAmount How much of the order is fillable
/// based on maker funds, in taker tokens.
/// @return isSignatureValid Whether the signature is valid.
function getRfqOrderRelevantState(
LibNativeOrder.RfqOrder calldata order,
LibSignature.Signature calldata signature
)
external
view
returns (
LibNativeOrder.OrderInfo memory orderInfo,
uint128 actualFillableTakerTokenAmount,
bool isSignatureValid
);
/// @dev Batch version of `getLimitOrderRelevantState()`, without reverting.
/// Orders that would normally cause `getLimitOrderRelevantState()`
/// to revert will have empty results.
/// @param orders The limit orders.
/// @param signatures The order signatures.
/// @return orderInfos Info about the orders.
/// @return actualFillableTakerTokenAmounts How much of each order is fillable
/// based on maker funds, in taker tokens.
/// @return isSignatureValids Whether each signature is valid for the order.
function batchGetLimitOrderRelevantStates(
LibNativeOrder.LimitOrder[] calldata orders,
LibSignature.Signature[] calldata signatures
)
external
view
returns (
LibNativeOrder.OrderInfo[] memory orderInfos,
uint128[] memory actualFillableTakerTokenAmounts,
bool[] memory isSignatureValids
);
/// @dev Batch version of `getRfqOrderRelevantState()`, without reverting.
/// Orders that would normally cause `getRfqOrderRelevantState()`
/// to revert will have empty results.
/// @param orders The RFQ orders.
/// @param signatures The order signatures.
/// @return orderInfos Info about the orders.
/// @return actualFillableTakerTokenAmounts How much of each order is fillable
/// based on maker funds, in taker tokens.
/// @return isSignatureValids Whether each signature is valid for the order.
function batchGetRfqOrderRelevantStates(
LibNativeOrder.RfqOrder[] calldata orders,
LibSignature.Signature[] calldata signatures
)
external
view
returns (
LibNativeOrder.OrderInfo[] memory orderInfos,
uint128[] memory actualFillableTakerTokenAmounts,
bool[] memory isSignatureValids
);
/// @dev Register a signer who can sign on behalf of msg.sender
/// This allows one to sign on behalf of a contract that calls this function
/// @param signer The address from which you plan to generate signatures
/// @param allowed True to register, false to unregister.
function registerAllowedOrderSigner(
address signer,
bool allowed
)
external;
/// @dev checks if a given address is registered to sign on behalf of a maker address
/// @param maker The maker address encoded in an order (can be a contract)
/// @param signer The address that is providing a signature
function isValidOrderSigner(
address maker,
address signer
)
external
view
returns (bool isAllowed);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
interface IWallet {
function registerAllowedOrderSigner(address signer, bool allowed) external;
function deposit(address[] calldata tokens, uint256[] calldata amounts) external;
function withdraw(address[] calldata tokens, uint256[] calldata amounts) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
interface IERC20TokenV06 {
// solhint-disable no-simple-event-func-name
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
/// @dev send `value` token to `to` from `msg.sender`
/// @param to The address of the recipient
/// @param value The amount of token to be transferred
/// @return True if transfer was successful
function transfer(address to, uint256 value)
external
returns (bool);
/// @dev send `value` token to `to` from `from` on the condition it is approved by `from`
/// @param from The address of the sender
/// @param to The address of the recipient
/// @param value The amount of token to be transferred
/// @return True if transfer was successful
function transferFrom(
address from,
address to,
uint256 value
)
external
returns (bool);
/// @dev `msg.sender` approves `spender` to spend `value` tokens
/// @param spender The address of the account able to transfer the tokens
/// @param value The amount of wei to be approved for transfer
/// @return Always true if the call has enough gas to complete execution
function approve(address spender, uint256 value)
external
returns (bool);
/// @dev Query total supply of token
/// @return Total supply of token
function totalSupply()
external
view
returns (uint256);
/// @dev Get the balance of `owner`.
/// @param owner The address from which the balance will be retrieved
/// @return Balance of owner
function balanceOf(address owner)
external
view
returns (uint256);
/// @dev Get the allowance for `spender` to spend from `owner`.
/// @param owner The address of the account owning tokens
/// @param spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address owner, address spender)
external
view
returns (uint256);
/// @dev Get the number of decimals this token has.
function decimals()
external
view
returns (uint8);
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "../../errors/LibSignatureRichErrors.sol";
/// @dev A library for validating signatures.
library LibSignature {
using LibRichErrorsV06 for bytes;
// '\x19Ethereum Signed Message:\n32\x00\x00\x00\x00' in a word.
uint256 private constant ETH_SIGN_HASH_PREFIX =
0x19457468657265756d205369676e6564204d6573736167653a0a333200000000;
/// @dev Exclusive upper limit on ECDSA signatures 'R' values.
/// The valid range is given by fig (282) of the yellow paper.
uint256 private constant ECDSA_SIGNATURE_R_LIMIT =
uint256(0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141);
/// @dev Exclusive upper limit on ECDSA signatures 'S' values.
/// The valid range is given by fig (283) of the yellow paper.
uint256 private constant ECDSA_SIGNATURE_S_LIMIT = ECDSA_SIGNATURE_R_LIMIT / 2 + 1;
/// @dev Allowed signature types.
enum SignatureType {
ILLEGAL,
INVALID,
EIP712,
ETHSIGN
}
/// @dev Encoded EC signature.
struct Signature {
// How to validate the signature.
SignatureType signatureType;
// EC Signature data.
uint8 v;
// EC Signature data.
bytes32 r;
// EC Signature data.
bytes32 s;
}
/// @dev Retrieve the signer of a signature.
/// Throws if the signature can't be validated.
/// @param hash The hash that was signed.
/// @param signature The signature.
/// @return recovered The recovered signer address.
function getSignerOfHash(
bytes32 hash,
Signature memory signature
)
internal
pure
returns (address recovered)
{
// Ensure this is a signature type that can be validated against a hash.
_validateHashCompatibleSignature(hash, signature);
if (signature.signatureType == SignatureType.EIP712) {
// Signed using EIP712
recovered = ecrecover(
hash,
signature.v,
signature.r,
signature.s
);
} else if (signature.signatureType == SignatureType.ETHSIGN) {
// Signed using `eth_sign`
// Need to hash `hash` with "\x19Ethereum Signed Message:\n32" prefix
// in packed encoding.
bytes32 ethSignHash;
assembly {
// Use scratch space
mstore(0, ETH_SIGN_HASH_PREFIX) // length of 28 bytes
mstore(28, hash) // length of 32 bytes
ethSignHash := keccak256(0, 60)
}
recovered = ecrecover(
ethSignHash,
signature.v,
signature.r,
signature.s
);
}
// `recovered` can be null if the signature values are out of range.
if (recovered == address(0)) {
LibSignatureRichErrors.SignatureValidationError(
LibSignatureRichErrors.SignatureValidationErrorCodes.BAD_SIGNATURE_DATA,
hash
).rrevert();
}
}
/// @dev Validates that a signature is compatible with a hash signee.
/// @param hash The hash that was signed.
/// @param signature The signature.
function _validateHashCompatibleSignature(
bytes32 hash,
Signature memory signature
)
private
pure
{
// Ensure the r and s are within malleability limits.
if (uint256(signature.r) >= ECDSA_SIGNATURE_R_LIMIT ||
uint256(signature.s) >= ECDSA_SIGNATURE_S_LIMIT)
{
LibSignatureRichErrors.SignatureValidationError(
LibSignatureRichErrors.SignatureValidationErrorCodes.BAD_SIGNATURE_DATA,
hash
).rrevert();
}
// Always illegal signature.
if (signature.signatureType == SignatureType.ILLEGAL) {
LibSignatureRichErrors.SignatureValidationError(
LibSignatureRichErrors.SignatureValidationErrorCodes.ILLEGAL,
hash
).rrevert();
}
// Always invalid.
if (signature.signatureType == SignatureType.INVALID) {
LibSignatureRichErrors.SignatureValidationError(
LibSignatureRichErrors.SignatureValidationErrorCodes.ALWAYS_INVALID,
hash
).rrevert();
}
// Solidity should check that the signature type is within enum range for us
// when abi-decoding.
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "../../errors/LibNativeOrdersRichErrors.sol";
/// @dev A library for common native order operations.
library LibNativeOrder {
using LibSafeMathV06 for uint256;
using LibRichErrorsV06 for bytes;
enum OrderStatus {
INVALID,
FILLABLE,
FILLED,
CANCELLED,
EXPIRED
}
/// @dev A standard OTC or OO limit order.
struct LimitOrder {
IERC20TokenV06 makerToken;
IERC20TokenV06 takerToken;
uint128 makerAmount;
uint128 takerAmount;
uint128 takerTokenFeeAmount;
address maker;
address taker;
address sender;
address feeRecipient;
bytes32 pool;
uint64 expiry;
uint256 salt;
}
/// @dev An RFQ limit order.
struct RfqOrder {
IERC20TokenV06 makerToken;
IERC20TokenV06 takerToken;
uint128 makerAmount;
uint128 takerAmount;
address maker;
address taker;
address txOrigin;
bytes32 pool;
uint64 expiry;
uint256 salt;
}
/// @dev An OTC limit order.
struct OtcOrder {
IERC20TokenV06 makerToken;
IERC20TokenV06 takerToken;
uint128 makerAmount;
uint128 takerAmount;
address maker;
address taker;
address txOrigin;
uint256 expiryAndNonce; // [uint64 expiry, uint64 nonceBucket, uint128 nonce]
}
/// @dev Info on a limit or RFQ order.
struct OrderInfo {
bytes32 orderHash;
OrderStatus status;
uint128 takerTokenFilledAmount;
}
/// @dev Info on an OTC order.
struct OtcOrderInfo {
bytes32 orderHash;
OrderStatus status;
}
uint256 private constant UINT_128_MASK = (1 << 128) - 1;
uint256 private constant UINT_64_MASK = (1 << 64) - 1;
uint256 private constant ADDRESS_MASK = (1 << 160) - 1;
// The type hash for limit orders, which is:
// keccak256(abi.encodePacked(
// "LimitOrder(",
// "address makerToken,",
// "address takerToken,",
// "uint128 makerAmount,",
// "uint128 takerAmount,",
// "uint128 takerTokenFeeAmount,",
// "address maker,",
// "address taker,",
// "address sender,",
// "address feeRecipient,",
// "bytes32 pool,",
// "uint64 expiry,",
// "uint256 salt"
// ")"
// ))
uint256 private constant _LIMIT_ORDER_TYPEHASH =
0xce918627cb55462ddbb85e73de69a8b322f2bc88f4507c52fcad6d4c33c29d49;
// The type hash for RFQ orders, which is:
// keccak256(abi.encodePacked(
// "RfqOrder(",
// "address makerToken,",
// "address takerToken,",
// "uint128 makerAmount,",
// "uint128 takerAmount,",
// "address maker,",
// "address taker,",
// "address txOrigin,",
// "bytes32 pool,",
// "uint64 expiry,",
// "uint256 salt"
// ")"
// ))
uint256 private constant _RFQ_ORDER_TYPEHASH =
0xe593d3fdfa8b60e5e17a1b2204662ecbe15c23f2084b9ad5bae40359540a7da9;
// The type hash for OTC orders, which is:
// keccak256(abi.encodePacked(
// "OtcOrder(",
// "address makerToken,",
// "address takerToken,",
// "uint128 makerAmount,",
// "uint128 takerAmount,",
// "address maker,",
// "address taker,",
// "address txOrigin,",
// "uint256 expiryAndNonce"
// ")"
// ))
uint256 private constant _OTC_ORDER_TYPEHASH =
0x2f754524de756ae72459efbe1ec88c19a745639821de528ac3fb88f9e65e35c8;
/// @dev Get the struct hash of a limit order.
/// @param order The limit order.
/// @return structHash The struct hash of the order.
function getLimitOrderStructHash(LimitOrder memory order)
internal
pure
returns (bytes32 structHash)
{
// The struct hash is:
// keccak256(abi.encode(
// TYPE_HASH,
// order.makerToken,
// order.takerToken,
// order.makerAmount,
// order.takerAmount,
// order.takerTokenFeeAmount,
// order.maker,
// order.taker,
// order.sender,
// order.feeRecipient,
// order.pool,
// order.expiry,
// order.salt,
// ))
assembly {
let mem := mload(0x40)
mstore(mem, _LIMIT_ORDER_TYPEHASH)
// order.makerToken;
mstore(add(mem, 0x20), and(ADDRESS_MASK, mload(order)))
// order.takerToken;
mstore(add(mem, 0x40), and(ADDRESS_MASK, mload(add(order, 0x20))))
// order.makerAmount;
mstore(add(mem, 0x60), and(UINT_128_MASK, mload(add(order, 0x40))))
// order.takerAmount;
mstore(add(mem, 0x80), and(UINT_128_MASK, mload(add(order, 0x60))))
// order.takerTokenFeeAmount;
mstore(add(mem, 0xA0), and(UINT_128_MASK, mload(add(order, 0x80))))
// order.maker;
mstore(add(mem, 0xC0), and(ADDRESS_MASK, mload(add(order, 0xA0))))
// order.taker;
mstore(add(mem, 0xE0), and(ADDRESS_MASK, mload(add(order, 0xC0))))
// order.sender;
mstore(add(mem, 0x100), and(ADDRESS_MASK, mload(add(order, 0xE0))))
// order.feeRecipient;
mstore(add(mem, 0x120), and(ADDRESS_MASK, mload(add(order, 0x100))))
// order.pool;
mstore(add(mem, 0x140), mload(add(order, 0x120)))
// order.expiry;
mstore(add(mem, 0x160), and(UINT_64_MASK, mload(add(order, 0x140))))
// order.salt;
mstore(add(mem, 0x180), mload(add(order, 0x160)))
structHash := keccak256(mem, 0x1A0)
}
}
/// @dev Get the struct hash of a RFQ order.
/// @param order The RFQ order.
/// @return structHash The struct hash of the order.
function getRfqOrderStructHash(RfqOrder memory order)
internal
pure
returns (bytes32 structHash)
{
// The struct hash is:
// keccak256(abi.encode(
// TYPE_HASH,
// order.makerToken,
// order.takerToken,
// order.makerAmount,
// order.takerAmount,
// order.maker,
// order.taker,
// order.txOrigin,
// order.pool,
// order.expiry,
// order.salt,
// ))
assembly {
let mem := mload(0x40)
mstore(mem, _RFQ_ORDER_TYPEHASH)
// order.makerToken;
mstore(add(mem, 0x20), and(ADDRESS_MASK, mload(order)))
// order.takerToken;
mstore(add(mem, 0x40), and(ADDRESS_MASK, mload(add(order, 0x20))))
// order.makerAmount;
mstore(add(mem, 0x60), and(UINT_128_MASK, mload(add(order, 0x40))))
// order.takerAmount;
mstore(add(mem, 0x80), and(UINT_128_MASK, mload(add(order, 0x60))))
// order.maker;
mstore(add(mem, 0xA0), and(ADDRESS_MASK, mload(add(order, 0x80))))
// order.taker;
mstore(add(mem, 0xC0), and(ADDRESS_MASK, mload(add(order, 0xA0))))
// order.txOrigin;
mstore(add(mem, 0xE0), and(ADDRESS_MASK, mload(add(order, 0xC0))))
// order.pool;
mstore(add(mem, 0x100), mload(add(order, 0xE0)))
// order.expiry;
mstore(add(mem, 0x120), and(UINT_64_MASK, mload(add(order, 0x100))))
// order.salt;
mstore(add(mem, 0x140), mload(add(order, 0x120)))
structHash := keccak256(mem, 0x160)
}
}
/// @dev Get the struct hash of an OTC order.
/// @param order The OTC order.
/// @return structHash The struct hash of the order.
function getOtcOrderStructHash(OtcOrder memory order)
internal
pure
returns (bytes32 structHash)
{
// The struct hash is:
// keccak256(abi.encode(
// TYPE_HASH,
// order.makerToken,
// order.takerToken,
// order.makerAmount,
// order.takerAmount,
// order.maker,
// order.taker,
// order.txOrigin,
// order.expiryAndNonce,
// ))
assembly {
let mem := mload(0x40)
mstore(mem, _OTC_ORDER_TYPEHASH)
// order.makerToken;
mstore(add(mem, 0x20), and(ADDRESS_MASK, mload(order)))
// order.takerToken;
mstore(add(mem, 0x40), and(ADDRESS_MASK, mload(add(order, 0x20))))
// order.makerAmount;
mstore(add(mem, 0x60), and(UINT_128_MASK, mload(add(order, 0x40))))
// order.takerAmount;
mstore(add(mem, 0x80), and(UINT_128_MASK, mload(add(order, 0x60))))
// order.maker;
mstore(add(mem, 0xA0), and(ADDRESS_MASK, mload(add(order, 0x80))))
// order.taker;
mstore(add(mem, 0xC0), and(ADDRESS_MASK, mload(add(order, 0xA0))))
// order.txOrigin;
mstore(add(mem, 0xE0), and(ADDRESS_MASK, mload(add(order, 0xC0))))
// order.expiryAndNonce;
mstore(add(mem, 0x100), mload(add(order, 0xE0)))
structHash := keccak256(mem, 0x120)
}
}
/// @dev Refund any leftover protocol fees in `msg.value` to `msg.sender`.
/// @param ethProtocolFeePaid How much ETH was paid in protocol fees.
function refundExcessProtocolFeeToSender(uint256 ethProtocolFeePaid)
internal
{
if (msg.value > ethProtocolFeePaid && msg.sender != address(this)) {
uint256 refundAmount = msg.value.safeSub(ethProtocolFeePaid);
(bool success,) = msg
.sender
.call{value: refundAmount}("");
if (!success) {
LibNativeOrdersRichErrors.ProtocolFeeRefundFailed(
msg.sender,
refundAmount
).rrevert();
}
}
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2021 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "../libs/LibSignature.sol";
import "../libs/LibNativeOrder.sol";
/// @dev Events emitted by NativeOrdersFeature.
interface INativeOrdersEvents {
/// @dev Emitted whenever a `LimitOrder` is filled.
/// @param orderHash The canonical hash of the order.
/// @param maker The maker of the order.
/// @param taker The taker of the order.
/// @param feeRecipient Fee recipient of the order.
/// @param takerTokenFilledAmount How much taker token was filled.
/// @param makerTokenFilledAmount How much maker token was filled.
/// @param protocolFeePaid How much protocol fee was paid.
/// @param pool The fee pool associated with this order.
event LimitOrderFilled(
bytes32 orderHash,
address maker,
address taker,
address feeRecipient,
address makerToken,
address takerToken,
uint128 takerTokenFilledAmount,
uint128 makerTokenFilledAmount,
uint128 takerTokenFeeFilledAmount,
uint256 protocolFeePaid,
bytes32 pool
);
/// @dev Emitted whenever an `RfqOrder` is filled.
/// @param orderHash The canonical hash of the order.
/// @param maker The maker of the order.
/// @param taker The taker of the order.
/// @param takerTokenFilledAmount How much taker token was filled.
/// @param makerTokenFilledAmount How much maker token was filled.
/// @param pool The fee pool associated with this order.
event RfqOrderFilled(
bytes32 orderHash,
address maker,
address taker,
address makerToken,
address takerToken,
uint128 takerTokenFilledAmount,
uint128 makerTokenFilledAmount,
bytes32 pool
);
/// @dev Emitted whenever a limit or RFQ order is cancelled.
/// @param orderHash The canonical hash of the order.
/// @param maker The order maker.
event OrderCancelled(
bytes32 orderHash,
address maker
);
/// @dev Emitted whenever Limit orders are cancelled by pair by a maker.
/// @param maker The maker of the order.
/// @param makerToken The maker token in a pair for the orders cancelled.
/// @param takerToken The taker token in a pair for the orders cancelled.
/// @param minValidSalt The new minimum valid salt an order with this pair must
/// have.
event PairCancelledLimitOrders(
address maker,
address makerToken,
address takerToken,
uint256 minValidSalt
);
/// @dev Emitted whenever RFQ orders are cancelled by pair by a maker.
/// @param maker The maker of the order.
/// @param makerToken The maker token in a pair for the orders cancelled.
/// @param takerToken The taker token in a pair for the orders cancelled.
/// @param minValidSalt The new minimum valid salt an order with this pair must
/// have.
event PairCancelledRfqOrders(
address maker,
address makerToken,
address takerToken,
uint256 minValidSalt
);
/// @dev Emitted when new addresses are allowed or disallowed to fill
/// orders with a given txOrigin.
/// @param origin The address doing the allowing.
/// @param addrs The address being allowed/disallowed.
/// @param allowed Indicates whether the address should be allowed.
event RfqOrderOriginsAllowed(
address origin,
address[] addrs,
bool allowed
);
/// @dev Emitted when new order signers are registered
/// @param maker The maker address that is registering a designated signer.
/// @param signer The address that will sign on behalf of maker.
/// @param allowed Indicates whether the address should be allowed.
event OrderSignerRegistered(
address maker,
address signer,
bool allowed
);
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibRichErrorsV06 {
// bytes4(keccak256("Error(string)"))
bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0;
// solhint-disable func-name-mixedcase
/// @dev ABI encode a standard, string revert error payload.
/// This is the same payload that would be included by a `revert(string)`
/// solidity statement. It has the function signature `Error(string)`.
/// @param message The error string.
/// @return The ABI encoded error.
function StandardError(string memory message)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
// solhint-enable func-name-mixedcase
/// @dev Reverts an encoded rich revert reason `errorData`.
/// @param errorData ABI encoded error data.
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibSignatureRichErrors {
enum SignatureValidationErrorCodes {
ALWAYS_INVALID,
INVALID_LENGTH,
UNSUPPORTED,
ILLEGAL,
WRONG_SIGNER,
BAD_SIGNATURE_DATA
}
// solhint-disable func-name-mixedcase
function SignatureValidationError(
SignatureValidationErrorCodes code,
bytes32 hash,
address signerAddress,
bytes memory signature
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("SignatureValidationError(uint8,bytes32,address,bytes)")),
code,
hash,
signerAddress,
signature
);
}
function SignatureValidationError(
SignatureValidationErrorCodes code,
bytes32 hash
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("SignatureValidationError(uint8,bytes32)")),
code,
hash
);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
import "./errors/LibRichErrorsV06.sol";
import "./errors/LibSafeMathRichErrorsV06.sol";
library LibSafeMathV06 {
function safeMul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (a == 0) {
return 0;
}
uint256 c = a * b;
if (c / a != b) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
a,
b
));
}
return c;
}
function safeDiv(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b == 0) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.DIVISION_BY_ZERO,
a,
b
));
}
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b > a) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
a,
b
));
}
return a - b;
}
function safeAdd(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
if (c < a) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.ADDITION_OVERFLOW,
a,
b
));
}
return c;
}
function max256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
function safeMul128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
if (a == 0) {
return 0;
}
uint128 c = a * b;
if (c / a != b) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
a,
b
));
}
return c;
}
function safeDiv128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
if (b == 0) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.DIVISION_BY_ZERO,
a,
b
));
}
uint128 c = a / b;
return c;
}
function safeSub128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
if (b > a) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
a,
b
));
}
return a - b;
}
function safeAdd128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
uint128 c = a + b;
if (c < a) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.ADDITION_OVERFLOW,
a,
b
));
}
return c;
}
function max128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
return a >= b ? a : b;
}
function min128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
return a < b ? a : b;
}
function safeDowncastToUint128(uint256 a)
internal
pure
returns (uint128)
{
if (a > type(uint128).max) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256DowncastError(
LibSafeMathRichErrorsV06.DowncastErrorCodes.VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT128,
a
));
}
return uint128(a);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibNativeOrdersRichErrors {
// solhint-disable func-name-mixedcase
function ProtocolFeeRefundFailed(
address receiver,
uint256 refundAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("ProtocolFeeRefundFailed(address,uint256)")),
receiver,
refundAmount
);
}
function OrderNotFillableByOriginError(
bytes32 orderHash,
address txOrigin,
address orderTxOrigin
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotFillableByOriginError(bytes32,address,address)")),
orderHash,
txOrigin,
orderTxOrigin
);
}
function OrderNotFillableError(
bytes32 orderHash,
uint8 orderStatus
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotFillableError(bytes32,uint8)")),
orderHash,
orderStatus
);
}
function OrderNotSignedByMakerError(
bytes32 orderHash,
address signer,
address maker
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotSignedByMakerError(bytes32,address,address)")),
orderHash,
signer,
maker
);
}
function OrderNotSignedByTakerError(
bytes32 orderHash,
address signer,
address taker
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotSignedByTakerError(bytes32,address,address)")),
orderHash,
signer,
taker
);
}
function InvalidSignerError(
address maker,
address signer
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InvalidSignerError(address,address)")),
maker,
signer
);
}
function OrderNotFillableBySenderError(
bytes32 orderHash,
address sender,
address orderSender
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotFillableBySenderError(bytes32,address,address)")),
orderHash,
sender,
orderSender
);
}
function OrderNotFillableByTakerError(
bytes32 orderHash,
address taker,
address orderTaker
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotFillableByTakerError(bytes32,address,address)")),
orderHash,
taker,
orderTaker
);
}
function CancelSaltTooLowError(
uint256 minValidSalt,
uint256 oldMinValidSalt
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("CancelSaltTooLowError(uint256,uint256)")),
minValidSalt,
oldMinValidSalt
);
}
function FillOrKillFailedError(
bytes32 orderHash,
uint256 takerTokenFilledAmount,
uint256 takerTokenFillAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("FillOrKillFailedError(bytes32,uint256,uint256)")),
orderHash,
takerTokenFilledAmount,
takerTokenFillAmount
);
}
function OnlyOrderMakerAllowed(
bytes32 orderHash,
address sender,
address maker
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OnlyOrderMakerAllowed(bytes32,address,address)")),
orderHash,
sender,
maker
);
}
function BatchFillIncompleteError(
bytes32 orderHash,
uint256 takerTokenFilledAmount,
uint256 takerTokenFillAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("BatchFillIncompleteError(bytes32,uint256,uint256)")),
orderHash,
takerTokenFilledAmount,
takerTokenFillAmount
);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibSafeMathRichErrorsV06 {
// bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)"))
bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR =
0xe946c1bb;
// bytes4(keccak256("Uint256DowncastError(uint8,uint256)"))
bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR =
0xc996af7b;
enum BinOpErrorCodes {
ADDITION_OVERFLOW,
MULTIPLICATION_OVERFLOW,
SUBTRACTION_UNDERFLOW,
DIVISION_BY_ZERO
}
enum DowncastErrorCodes {
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT128
}
// solhint-disable func-name-mixedcase
function Uint256BinOpError(
BinOpErrorCodes errorCode,
uint256 a,
uint256 b
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_BINOP_ERROR_SELECTOR,
errorCode,
a,
b
);
}
function Uint256DowncastError(
DowncastErrorCodes errorCode,
uint256 a
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_DOWNCAST_ERROR_SELECTOR,
errorCode,
a
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/IWallet.sol";
contract ZeroExController {
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using SafeMath for uint256;
// solhint-disable-next-line
IWallet public immutable WALLET;
constructor(IWallet wallet) public {
require(address(wallet) != address(0), "INVALID_WALLET");
WALLET = wallet;
}
function deploy(bytes calldata data) external {
(address[] memory tokens, uint256[] memory amounts) = abi.decode(
data,
(address[], uint256[])
);
uint256 tokensLength = tokens.length;
for (uint256 i = 0; i < tokensLength; i++) {
_approve(IERC20(tokens[i]), amounts[i]);
}
WALLET.deposit(tokens, amounts);
}
function withdraw(bytes calldata data) external {
(address[] memory tokens, uint256[] memory amounts) = abi.decode(
data,
(address[], uint256[])
);
WALLET.withdraw(tokens, amounts);
}
function _approve(IERC20 token, uint256 amount) internal {
uint256 currentAllowance = token.allowance(address(this), address(WALLET));
if (currentAllowance < amount) {
token.safeIncreaseAllowance(address(WALLET), type(uint256).max.sub(currentAllowance));
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "../interfaces/IManager.sol";
import "../interfaces/ILiquidityPool.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable as SafeERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import {EnumerableSetUpgradeable as EnumerableSet} from "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import {SafeMathUpgradeable as SafeMath} from "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import {AccessControlUpgradeable as AccessControl} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
contract Manager is IManager, Initializable, AccessControl {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.Bytes32Set;
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
bytes32 public constant ROLLOVER_ROLE = keccak256("ROLLOVER_ROLE");
bytes32 public constant MID_CYCLE_ROLE = keccak256("MID_CYCLE_ROLE");
uint256 public currentCycle;
uint256 public currentCycleIndex;
uint256 public cycleDuration;
bool public rolloverStarted;
mapping(bytes32 => address) public registeredControllers;
mapping(uint256 => string) public override cycleRewardsHashes;
EnumerableSet.AddressSet private pools;
EnumerableSet.Bytes32Set private controllerIds;
modifier onlyAdmin() {
require(hasRole(ADMIN_ROLE, _msgSender()), "NOT_ADMIN_ROLE");
_;
}
modifier onlyRollover() {
require(hasRole(ROLLOVER_ROLE, _msgSender()), "NOT_ROLLOVER_ROLE");
_;
}
modifier onlyMidCycle() {
require(hasRole(MID_CYCLE_ROLE, _msgSender()), "NOT_MID_CYCLE_ROLE");
_;
}
function initialize(uint256 _cycleDuration) public initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
cycleDuration = _cycleDuration;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(ADMIN_ROLE, _msgSender());
_setupRole(ROLLOVER_ROLE, _msgSender());
_setupRole(MID_CYCLE_ROLE, _msgSender());
}
function registerController(bytes32 id, address controller) external override onlyAdmin {
require(!controllerIds.contains(id), "CONTROLLER_EXISTS");
registeredControllers[id] = controller;
controllerIds.add(id);
emit ControllerRegistered(id, controller);
}
function unRegisterController(bytes32 id) external override onlyAdmin {
require(controllerIds.contains(id), "INVALID_CONTROLLER");
emit ControllerUnregistered(id, registeredControllers[id]);
delete registeredControllers[id];
controllerIds.remove(id);
}
function registerPool(address pool) external override onlyAdmin {
require(!pools.contains(pool), "POOL_EXISTS");
pools.add(pool);
emit PoolRegistered(pool);
}
function unRegisterPool(address pool) external override onlyAdmin {
require(pools.contains(pool), "INVALID_POOL");
pools.remove(pool);
emit PoolUnregistered(pool);
}
function setCycleDuration(uint256 duration) external override onlyAdmin {
cycleDuration = duration;
emit CycleDurationSet(duration);
}
function getPools() external view override returns (address[] memory) {
address[] memory returnData = new address[](pools.length());
for (uint256 i = 0; i < pools.length(); i++) {
returnData[i] = pools.at(i);
}
return returnData;
}
function getControllers() external view override returns (bytes32[] memory) {
bytes32[] memory returnData = new bytes32[](controllerIds.length());
for (uint256 i = 0; i < controllerIds.length(); i++) {
returnData[i] = controllerIds.at(i);
}
return returnData;
}
function completeRollover(string calldata rewardsIpfsHash) external override onlyRollover {
require(block.number > (currentCycle.add(cycleDuration)), "PREMATURE_EXECUTION");
_completeRollover(rewardsIpfsHash);
}
function executeMaintenance(MaintenanceExecution calldata params)
external
override
onlyMidCycle
{
for (uint256 x = 0; x < params.cycleSteps.length; x++) {
_executeControllerCommand(params.cycleSteps[x]);
}
}
function executeRollover(RolloverExecution calldata params) external override onlyRollover {
require(block.number > (currentCycle.add(cycleDuration)), "PREMATURE_EXECUTION");
// Transfer deployable liquidity out of the pools and into the manager
for (uint256 i = 0; i < params.poolData.length; i++) {
require(pools.contains(params.poolData[i].pool), "INVALID_POOL");
ILiquidityPool pool = ILiquidityPool(params.poolData[i].pool);
IERC20 underlyingToken = pool.underlyer();
underlyingToken.safeTransferFrom(
address(pool),
address(this),
params.poolData[i].amount
);
emit LiquidityMovedToManager(params.poolData[i].pool, params.poolData[i].amount);
}
// Deploy or withdraw liquidity
for (uint256 x = 0; x < params.cycleSteps.length; x++) {
_executeControllerCommand(params.cycleSteps[x]);
}
// Transfer recovered liquidity back into the pools; leave no funds in the manager
for (uint256 y = 0; y < params.poolsForWithdraw.length; y++) {
require(pools.contains(params.poolsForWithdraw[y]), "INVALID_POOL");
ILiquidityPool pool = ILiquidityPool(params.poolsForWithdraw[y]);
IERC20 underlyingToken = pool.underlyer();
uint256 managerBalance = underlyingToken.balanceOf(address(this));
// transfer funds back to the pool if there are funds
if (managerBalance > 0) {
underlyingToken.safeTransfer(address(pool), managerBalance);
}
emit LiquidityMovedToPool(params.poolsForWithdraw[y], managerBalance);
}
if (params.complete) {
_completeRollover(params.rewardsIpfsHash);
}
}
function _executeControllerCommand(ControllerTransferData calldata transfer) private {
address controllerAddress = registeredControllers[transfer.controllerId];
require(controllerAddress != address(0), "INVALID_CONTROLLER");
controllerAddress.functionDelegateCall(transfer.data, "CYCLE_STEP_EXECUTE_FAILED");
emit DeploymentStepExecuted(transfer.controllerId, controllerAddress, transfer.data);
}
function startCycleRollover() external override onlyRollover {
rolloverStarted = true;
emit CycleRolloverStarted(block.number);
}
function _completeRollover(string calldata rewardsIpfsHash) private {
currentCycle = block.number;
cycleRewardsHashes[currentCycleIndex] = rewardsIpfsHash;
currentCycleIndex = currentCycleIndex.add(1);
rolloverStarted = false;
emit CycleRolloverComplete(block.number);
}
function getCurrentCycle() external view override returns (uint256) {
return currentCycle;
}
function getCycleDuration() external view override returns (uint256) {
return cycleDuration;
}
function getCurrentCycleIndex() external view override returns (uint256) {
return currentCycleIndex;
}
function getRolloverStatus() external view override returns (bool) {
return rolloverStarted;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
interface IManager {
// bytes can take on the form of deploying or recovering liquidity
struct ControllerTransferData {
bytes32 controllerId; // controller to target
bytes data; // data the controller will pass
}
struct PoolTransferData {
address pool; // pool to target
uint256 amount; // amount to transfer
}
struct MaintenanceExecution {
ControllerTransferData[] cycleSteps;
}
struct RolloverExecution {
PoolTransferData[] poolData;
ControllerTransferData[] cycleSteps;
address[] poolsForWithdraw; //Pools to target for manager -> pool transfer
bool complete; //Whether to mark the rollover complete
string rewardsIpfsHash;
}
event ControllerRegistered(bytes32 id, address controller);
event ControllerUnregistered(bytes32 id, address controller);
event PoolRegistered(address pool);
event PoolUnregistered(address pool);
event CycleDurationSet(uint256 duration);
event LiquidityMovedToManager(address pool, uint256 amount);
event DeploymentStepExecuted(bytes32 controller, address adapaterAddress, bytes data);
event LiquidityMovedToPool(address pool, uint256 amount);
event CycleRolloverStarted(uint256 blockNumber);
event CycleRolloverComplete(uint256 blockNumber);
function registerController(bytes32 id, address controller) external;
function registerPool(address pool) external;
function unRegisterController(bytes32 id) external;
function unRegisterPool(address pool) external;
function getPools() external view returns (address[] memory);
function getControllers() external view returns (bytes32[] memory);
function setCycleDuration(uint256 duration) external;
function startCycleRollover() external;
function executeMaintenance(MaintenanceExecution calldata params) external;
function executeRollover(RolloverExecution calldata params) external;
function completeRollover(string calldata rewardsIpfsHash) external;
function cycleRewardsHashes(uint256 index) external view returns (string memory);
function getCurrentCycle() external view returns (uint256);
function getCurrentCycleIndex() external view returns (uint256);
function getCycleDuration() external view returns (uint256);
function getRolloverStatus() external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "../interfaces/IManager.sol";
/// @title Interface for Pool
/// @notice Allows users to deposit ERC-20 tokens to be deployed to market makers.
/// @notice Mints 1:1 fToken on deposit, represeting an IOU for the undelrying token that is freely transferable.
/// @notice Holders of fTokens earn rewards based on duration their tokens were deployed and the demand for that asset.
/// @notice Holders of fTokens can redeem for underlying asset after issuing requestWithdrawal and waiting for the next cycle.
interface ILiquidityPool {
struct WithdrawalInfo {
uint256 minCycle;
uint256 amount;
}
/// @notice Transfers amount of underlying token from user to this pool and mints fToken to the msg.sender.
/// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract.
/// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld.
function deposit(uint256 amount) external;
/// @notice Transfers amount of underlying token from user to this pool and mints fToken to the account.
/// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract.
/// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld.
function depositFor(address account, uint256 amount) external;
/// @notice Requests that the manager prepare funds for withdrawal next cycle
/// @notice Invoking this function when sender already has a currently pending request will overwrite that requested amount and reset the cycle timer
/// @param amount Amount of fTokens requested to be redeemed
function requestWithdrawal(uint256 amount) external;
function approveManager(uint256 amount) external;
/// @notice Sender must first invoke requestWithdrawal in a previous cycle
/// @notice This function will burn the fAsset and transfers underlying asset back to sender
/// @notice Will execute a partial withdrawal if either available liquidity or previously requested amount is insufficient
/// @param amount Amount of fTokens to redeem, value can be in excess of available tokens, operation will be reduced to maximum permissible
function withdraw(uint256 amount) external;
/// @return Reference to the underlying ERC-20 contract
function underlyer() external view returns (ERC20Upgradeable);
/// @return Amount of liquidity that should not be deployed for market making (this liquidity will be used for completing requested withdrawals)
function withheldLiquidity() external view returns (uint256);
/// @notice Get withdraw requests for an account
/// @param account User account to check
/// @return minCycle Cycle - block number - that must be active before withdraw is allowed, amount Token amount requested
function requestedWithdrawals(address account) external view returns (uint256, uint256);
/// @notice Pause deposits on the pool. Withdraws still allowed
function pause() external;
/// @notice Unpause deposits on the pool.
function unpause() external;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSetUpgradeable.sol";
import "../utils/AddressUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
struct RoleData {
EnumerableSetUpgradeable.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "../interfaces/IStaking.sol";
import "../interfaces/IManager.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {SafeMathUpgradeable as SafeMath} from "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import {MathUpgradeable as Math} from "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol";
import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable as SafeERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import {OwnableUpgradeable as Ownable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {EnumerableSetUpgradeable as EnumerableSet} from "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import {PausableUpgradeable as Pausable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
contract Staking is IStaking, Initializable, Ownable, Pausable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.UintSet;
IERC20 public tokeToken;
IManager public manager;
address public treasury;
uint256 public withheldLiquidity;
//userAddress -> withdrawalInfo
mapping(address => WithdrawalInfo) public requestedWithdrawals;
//userAddress -> -> scheduleIndex -> staking detail
mapping(address => mapping(uint256 => StakingDetails)) public userStakings;
//userAddress -> scheduleIdx[]
mapping(address => uint256[]) public userStakingSchedules;
//Schedule id/index counter
uint256 public nextScheduleIndex;
//scheduleIndex/id -> schedule
mapping(uint256 => StakingSchedule) public schedules;
//scheduleIndex/id[]
EnumerableSet.UintSet private scheduleIdxs;
//Can deposit into a non-public schedule
mapping(address => bool) public override permissionedDepositors;
modifier onlyPermissionedDepositors() {
require(_isAllowedPermissionedDeposit(), "CALLER_NOT_PERMISSIONED");
_;
}
function initialize(
IERC20 _tokeToken,
IManager _manager,
address _treasury
) public initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__Pausable_init_unchained();
require(address(_tokeToken) != address(0), "INVALID_TOKETOKEN");
require(address(_manager) != address(0), "INVALID_MANAGER");
require(_treasury != address(0), "INVALID_TREASURY");
tokeToken = _tokeToken;
manager = _manager;
treasury = _treasury;
//We want to be sure the schedule used for LP staking is first
//because the order in which withdraws happen need to start with LP stakes
_addSchedule(
StakingSchedule({
cliff: 0,
duration: 1,
interval: 1,
setup: true,
isActive: true,
hardStart: 0,
isPublic: true
})
);
}
function addSchedule(StakingSchedule memory schedule) external override onlyOwner {
_addSchedule(schedule);
}
function setPermissionedDepositor(address account, bool canDeposit)
external
override
onlyOwner
{
permissionedDepositors[account] = canDeposit;
}
function setUserSchedules(address account, uint256[] calldata userSchedulesIdxs)
external
override
onlyOwner
{
userStakingSchedules[account] = userSchedulesIdxs;
}
function getSchedules()
external
view
override
returns (StakingScheduleInfo[] memory retSchedules)
{
uint256 length = scheduleIdxs.length();
retSchedules = new StakingScheduleInfo[](length);
for (uint256 i = 0; i < length; i++) {
retSchedules[i] = StakingScheduleInfo(
schedules[scheduleIdxs.at(i)],
scheduleIdxs.at(i)
);
}
}
function removeSchedule(uint256 scheduleIndex) external override onlyOwner {
require(scheduleIdxs.contains(scheduleIndex), "INVALID_SCHEDULE");
scheduleIdxs.remove(scheduleIndex);
delete schedules[scheduleIndex];
emit ScheduleRemoved(scheduleIndex);
}
function getStakes(address account)
external
view
override
returns (StakingDetails[] memory stakes)
{
stakes = _getStakes(account);
}
function balanceOf(address account) external view override returns (uint256 value) {
value = 0;
uint256 scheduleCount = userStakingSchedules[account].length;
for (uint256 i = 0; i < scheduleCount; i++) {
uint256 remaining = userStakings[account][userStakingSchedules[account][i]].initial.sub(
userStakings[account][userStakingSchedules[account][i]].withdrawn
);
uint256 slashed = userStakings[account][userStakingSchedules[account][i]].slashed;
if (remaining > slashed) {
value = value.add(remaining.sub(slashed));
}
}
}
function availableForWithdrawal(address account, uint256 scheduleIndex)
external
view
override
returns (uint256)
{
return _availableForWithdrawal(account, scheduleIndex);
}
function unvested(address account, uint256 scheduleIndex)
external
view
override
returns (uint256 value)
{
value = 0;
StakingDetails memory stake = userStakings[account][scheduleIndex];
value = stake.initial.sub(_vested(account, scheduleIndex));
}
function vested(address account, uint256 scheduleIndex)
external
view
override
returns (uint256 value)
{
return _vested(account, scheduleIndex);
}
function deposit(uint256 amount, uint256 scheduleIndex) external override {
_depositFor(msg.sender, amount, scheduleIndex);
}
function depositFor(
address account,
uint256 amount,
uint256 scheduleIndex
) external override {
_depositFor(account, amount, scheduleIndex);
}
function depositWithSchedule(
address account,
uint256 amount,
StakingSchedule calldata schedule
) external override onlyPermissionedDepositors {
uint256 scheduleIx = nextScheduleIndex;
_addSchedule(schedule);
_depositFor(account, amount, scheduleIx);
}
function requestWithdrawal(uint256 amount) external override {
require(amount > 0, "INVALID_AMOUNT");
StakingDetails[] memory stakes = _getStakes(msg.sender);
uint256 length = stakes.length;
uint256 stakedAvailable = 0;
for (uint256 i = 0; i < length; i++) {
stakedAvailable = stakedAvailable.add(
_availableForWithdrawal(msg.sender, stakes[i].scheduleIx)
);
}
require(stakedAvailable >= amount, "INSUFFICIENT_AVAILABLE");
withheldLiquidity = withheldLiquidity.sub(requestedWithdrawals[msg.sender].amount).add(
amount
);
requestedWithdrawals[msg.sender].amount = amount;
if (manager.getRolloverStatus()) {
requestedWithdrawals[msg.sender].minCycleIndex = manager.getCurrentCycleIndex().add(2);
} else {
requestedWithdrawals[msg.sender].minCycleIndex = manager.getCurrentCycleIndex().add(1);
}
emit WithdrawalRequested(msg.sender, amount);
}
function withdraw(uint256 amount) external override {
require(amount <= requestedWithdrawals[msg.sender].amount, "WITHDRAW_INSUFFICIENT_BALANCE");
require(amount > 0, "NO_WITHDRAWAL");
require(
requestedWithdrawals[msg.sender].minCycleIndex <= manager.getCurrentCycleIndex(),
"INVALID_CYCLE"
);
StakingDetails[] memory stakes = _getStakes(msg.sender);
uint256 available = 0;
uint256 length = stakes.length;
uint256 remainingAmount = amount;
uint256 stakedAvailable = 0;
for (uint256 i = 0; i < length && remainingAmount > 0; i++) {
stakedAvailable = _availableForWithdrawal(msg.sender, stakes[i].scheduleIx);
available = available.add(stakedAvailable);
if (stakedAvailable < remainingAmount) {
remainingAmount = remainingAmount.sub(stakedAvailable);
stakes[i].withdrawn = stakes[i].withdrawn.add(stakedAvailable);
} else {
stakes[i].withdrawn = stakes[i].withdrawn.add(remainingAmount);
remainingAmount = 0;
}
userStakings[msg.sender][stakes[i].scheduleIx] = stakes[i];
}
require(remainingAmount == 0, "INSUFFICIENT_AVAILABLE"); //May not need to check this again
requestedWithdrawals[msg.sender].amount = requestedWithdrawals[msg.sender].amount.sub(
amount
);
if (requestedWithdrawals[msg.sender].amount == 0) {
delete requestedWithdrawals[msg.sender];
}
withheldLiquidity = withheldLiquidity.sub(amount);
tokeToken.safeTransfer(msg.sender, amount);
emit WithdrawCompleted(msg.sender, amount);
}
function slash(
address account,
uint256 amount,
uint256 scheduleIndex
) external onlyOwner {
StakingSchedule storage schedule = schedules[scheduleIndex];
require(amount > 0, "INVALID_AMOUNT");
require(schedule.setup, "INVALID_SCHEDULE");
StakingDetails memory userStake = userStakings[account][scheduleIndex];
require(userStake.initial > 0, "NO_VESTING");
uint256 availableToSlash = 0;
uint256 remaining = userStake.initial.sub(userStake.withdrawn);
if (remaining > userStake.slashed) {
availableToSlash = remaining.sub(userStake.slashed);
}
require(availableToSlash >= amount, "INSUFFICIENT_AVAILABLE");
userStake.slashed = userStake.slashed.add(amount);
userStakings[account][scheduleIndex] = userStake;
tokeToken.safeTransfer(treasury, amount);
emit Slashed(account, amount, scheduleIndex);
}
function pause() external override onlyOwner {
_pause();
}
function unpause() external override onlyOwner {
_unpause();
}
function _availableForWithdrawal(address account, uint256 scheduleIndex)
private
view
returns (uint256)
{
StakingDetails memory stake = userStakings[account][scheduleIndex];
uint256 vestedWoWithdrawn = _vested(account, scheduleIndex).sub(stake.withdrawn);
if (stake.slashed > vestedWoWithdrawn) return 0;
return vestedWoWithdrawn.sub(stake.slashed);
}
function _depositFor(
address account,
uint256 amount,
uint256 scheduleIndex
) private {
StakingSchedule memory schedule = schedules[scheduleIndex];
require(!paused(), "Pausable: paused");
require(amount > 0, "INVALID_AMOUNT");
require(schedule.setup, "INVALID_SCHEDULE");
require(schedule.isActive, "INACTIVE_SCHEDULE");
require(account != address(0), "INVALID_ADDRESS");
require(schedule.isPublic || _isAllowedPermissionedDeposit(), "PERMISSIONED_SCHEDULE");
StakingDetails memory userStake = userStakings[account][scheduleIndex];
if (userStake.initial == 0) {
userStakingSchedules[account].push(scheduleIndex);
}
userStake.initial = userStake.initial.add(amount);
if (schedule.hardStart > 0) {
userStake.started = schedule.hardStart;
} else {
// solhint-disable-next-line not-rely-on-time
userStake.started = block.timestamp;
}
userStake.scheduleIx = scheduleIndex;
userStakings[account][scheduleIndex] = userStake;
tokeToken.safeTransferFrom(msg.sender, address(this), amount);
emit Deposited(account, amount, scheduleIndex);
}
function _vested(address account, uint256 scheduleIndex) private view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
uint256 timestamp = block.timestamp;
uint256 value = 0;
StakingDetails memory stake = userStakings[account][scheduleIndex];
StakingSchedule memory schedule = schedules[scheduleIndex];
uint256 cliffTimestamp = stake.started.add(schedule.cliff);
if (cliffTimestamp <= timestamp) {
if (cliffTimestamp.add(schedule.duration) <= timestamp) {
value = stake.initial;
} else {
uint256 secondsStaked = Math.max(timestamp.sub(cliffTimestamp), 1);
uint256 effectiveSecondsStaked = (secondsStaked.mul(schedule.interval)).div(
schedule.interval
);
value = stake.initial.mul(effectiveSecondsStaked).div(schedule.duration);
}
}
return value;
}
function _addSchedule(StakingSchedule memory schedule) private {
require(schedule.duration > 0, "INVALID_DURATION");
require(schedule.interval > 0, "INVALID_INTERVAL");
schedule.setup = true;
uint256 index = nextScheduleIndex;
schedules[index] = schedule;
scheduleIdxs.add(index);
nextScheduleIndex = nextScheduleIndex.add(1);
emit ScheduleAdded(
index,
schedule.cliff,
schedule.duration,
schedule.interval,
schedule.setup,
schedule.isActive,
schedule.hardStart
);
}
function _getStakes(address account) private view returns (StakingDetails[] memory stakes) {
uint256 stakeCnt = userStakingSchedules[account].length;
stakes = new StakingDetails[](stakeCnt);
for (uint256 i = 0; i < stakeCnt; i++) {
stakes[i] = userStakings[account][userStakingSchedules[account][i]];
}
}
function _isAllowedPermissionedDeposit() private view returns (bool) {
return permissionedDepositors[msg.sender] || msg.sender == owner();
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
interface IStaking {
struct StakingSchedule {
uint256 cliff; // Duration in seconds before staking starts
uint256 duration; // Seconds it takes for entire amount to stake
uint256 interval; // Seconds it takes for a chunk to stake
bool setup; //Just so we know its there
bool isActive; //Whether we can setup new stakes with the schedule
uint256 hardStart; //Stakings will always start at this timestamp if set
bool isPublic; //Schedule can be written to by any account
}
struct StakingScheduleInfo {
StakingSchedule schedule;
uint256 index;
}
struct StakingDetails {
uint256 initial; //Initial amount of asset when stake was created, total amount to be staked before slashing
uint256 withdrawn; //Amount that was staked and subsequently withdrawn
uint256 slashed; //Amount that has been slashed
uint256 started; //Timestamp at which the stake started
uint256 scheduleIx;
}
struct WithdrawalInfo {
uint256 minCycleIndex;
uint256 amount;
}
event ScheduleAdded(uint256 scheduleIndex, uint256 cliff, uint256 duration, uint256 interval, bool setup, bool isActive, uint256 hardStart);
event ScheduleRemoved(uint256 scheduleIndex);
event WithdrawalRequested(address account, uint256 amount);
event WithdrawCompleted(address account, uint256 amount);
event Deposited(address account, uint256 amount, uint256 scheduleIx);
event Slashed(address account, uint256 amount, uint256 scheduleIx);
function permissionedDepositors(address account) external returns (bool);
function setUserSchedules(address account, uint256[] calldata userSchedulesIdxs) external;
function addSchedule(StakingSchedule memory schedule) external;
function getSchedules() external view returns (StakingScheduleInfo[] memory);
function setPermissionedDepositor(address account, bool canDeposit) external;
function removeSchedule(uint256 scheduleIndex) external;
function getStakes(address account) external view returns(StakingDetails[] memory);
function balanceOf(address account) external view returns(uint256);
function availableForWithdrawal(address account, uint256 scheduleIndex) external view returns (uint256);
function unvested(address account, uint256 scheduleIndex) external view returns(uint256);
function vested(address account, uint256 scheduleIndex) external view returns(uint256);
function deposit(uint256 amount, uint256 scheduleIndex) external;
function depositFor(address account, uint256 amount, uint256 scheduleIndex) external;
function depositWithSchedule(address account, uint256 amount, StakingSchedule calldata schedule) external;
function requestWithdrawal(uint256 amount) external;
function withdraw(uint256 amount) external;
/// @notice Pause deposits on the pool. Withdraws still allowed
function pause() external;
/// @notice Unpause deposits on the pool.
function unpause() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "../interfaces/ILiquidityPool.sol";
import "../interfaces/IManager.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {SafeMathUpgradeable as SafeMath} from "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import {MathUpgradeable as Math} from "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol";
import {OwnableUpgradeable as Ownable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {ERC20Upgradeable as ERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable as SafeERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import {PausableUpgradeable as Pausable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
contract Pool is ILiquidityPool, Initializable, ERC20, Ownable, Pausable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
ERC20 public override underlyer;
IManager public manager;
// implied: deployableLiquidity = underlyer.balanceOf(this) - withheldLiquidity
uint256 public override withheldLiquidity;
// fAsset holder -> WithdrawalInfo
mapping(address => WithdrawalInfo) public override requestedWithdrawals;
function initialize(
ERC20 _underlyer,
IManager _manager,
string memory _name,
string memory _symbol
) public initializer {
require(address(_underlyer) != address(0), "ZERO_ADDRESS");
require(address(_manager) != address(0), "ZERO_ADDRESS");
__Context_init_unchained();
__Ownable_init_unchained();
__Pausable_init_unchained();
__ERC20_init_unchained(_name, _symbol);
underlyer = _underlyer;
manager = _manager;
}
function decimals() public view override returns (uint8) {
return underlyer.decimals();
}
function deposit(uint256 amount) external override whenNotPaused {
_deposit(msg.sender, msg.sender, amount);
}
function depositFor(address account, uint256 amount) external override whenNotPaused {
_deposit(msg.sender, account, amount);
}
/// @dev References the WithdrawalInfo for how much the user is permitted to withdraw
/// @dev No withdrawal permitted unless currentCycle >= minCycle
/// @dev Decrements withheldLiquidity by the withdrawn amount
/// @dev TODO Update rewardsContract with proper accounting
function withdraw(uint256 requestedAmount) external override whenNotPaused {
require(
requestedAmount <= requestedWithdrawals[msg.sender].amount,
"WITHDRAW_INSUFFICIENT_BALANCE"
);
require(requestedAmount > 0, "NO_WITHDRAWAL");
require(underlyer.balanceOf(address(this)) >= requestedAmount, "INSUFFICIENT_POOL_BALANCE");
require(
requestedWithdrawals[msg.sender].minCycle <= manager.getCurrentCycleIndex(),
"INVALID_CYCLE"
);
requestedWithdrawals[msg.sender].amount = requestedWithdrawals[msg.sender].amount.sub(
requestedAmount
);
if (requestedWithdrawals[msg.sender].amount == 0) {
delete requestedWithdrawals[msg.sender];
}
withheldLiquidity = withheldLiquidity.sub(requestedAmount);
_burn(msg.sender, requestedAmount);
underlyer.safeTransfer(msg.sender, requestedAmount);
}
/// @dev Adjusts the withheldLiquidity as necessary
/// @dev Updates the WithdrawalInfo for when a user can withdraw and for what requested amount
function requestWithdrawal(uint256 amount) external override {
require(amount > 0, "INVALID_AMOUNT");
require(amount <= balanceOf(msg.sender), "INSUFFICIENT_BALANCE");
//adjust withheld liquidity by removing the original withheld amount and adding the new amount
withheldLiquidity = withheldLiquidity.sub(requestedWithdrawals[msg.sender].amount).add(
amount
);
requestedWithdrawals[msg.sender].amount = amount;
if (manager.getRolloverStatus()) {
requestedWithdrawals[msg.sender].minCycle = manager.getCurrentCycleIndex().add(2);
} else {
requestedWithdrawals[msg.sender].minCycle = manager.getCurrentCycleIndex().add(1);
}
}
function preTransferAdjustWithheldLiquidity(address sender, uint256 amount) internal {
if (requestedWithdrawals[sender].amount > 0) {
//reduce requested withdraw amount by transferred amount;
uint256 newRequestedWithdrawl = requestedWithdrawals[sender].amount.sub(
Math.min(amount, requestedWithdrawals[sender].amount)
);
//subtract from global withheld liquidity (reduce) by removing the delta of (requestedAmount - newRequestedAmount)
withheldLiquidity = withheldLiquidity.sub(
requestedWithdrawals[sender].amount.sub(newRequestedWithdrawl)
);
//update the requested withdraw for user
requestedWithdrawals[sender].amount = newRequestedWithdrawl;
//if the withdraw request is 0, empty it out
if (requestedWithdrawals[sender].amount == 0) {
delete requestedWithdrawals[sender];
}
}
}
function approveManager(uint256 amount) public override onlyOwner {
uint256 currentAllowance = underlyer.allowance(address(this), address(manager));
if (currentAllowance < amount) {
uint256 delta = amount.sub(currentAllowance);
underlyer.safeIncreaseAllowance(address(manager), delta);
} else {
uint256 delta = currentAllowance.sub(amount);
underlyer.safeDecreaseAllowance(address(manager), delta);
}
}
/// @dev Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer
function transfer(address recipient, uint256 amount)
public
override
whenNotPaused
returns (bool)
{
preTransferAdjustWithheldLiquidity(msg.sender, amount);
return super.transfer(recipient, amount);
}
/// @dev Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override whenNotPaused returns (bool) {
preTransferAdjustWithheldLiquidity(sender, amount);
return super.transferFrom(sender, recipient, amount);
}
function pause() external override onlyOwner {
_pause();
}
function unpause() external override onlyOwner {
_unpause();
}
function _deposit(
address fromAccount,
address toAccount,
uint256 amount
) internal {
require(amount > 0, "INVALID_AMOUNT");
require(toAccount != address(0), "INVALID_ADDRESS");
_mint(toAccount, amount);
underlyer.safeTransferFrom(fromAccount, address(this), amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "../interfaces/ILiquidityEthPool.sol";
import "../interfaces/IManager.sol";
import "../interfaces/IWETH.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {AddressUpgradeable as Address} from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import {MathUpgradeable as Math} from "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol";
import {SafeMathUpgradeable as SafeMath} from "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import {OwnableUpgradeable as Ownable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {ERC20Upgradeable as ERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable as SafeERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import {PausableUpgradeable as Pausable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
contract EthPool is ILiquidityEthPool, Initializable, ERC20, Ownable, Pausable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
/// @dev TODO: Hardcode addresses, make immuatable, remove from initializer
IWETH public override weth;
IManager public manager;
// implied: deployableLiquidity = underlyer.balanceOf(this) - withheldLiquidity
uint256 public override withheldLiquidity;
// fAsset holder -> WithdrawalInfo
mapping(address => WithdrawalInfo) public override requestedWithdrawals;
/// @dev necessary to receive ETH
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
function initialize(
IWETH _weth,
IManager _manager,
string memory _name,
string memory _symbol
) public initializer {
require(address(_weth) != address(0), "ZERO_ADDRESS");
require(address(_manager) != address(0), "ZERO_ADDRESS");
__Context_init_unchained();
__Ownable_init_unchained();
__Pausable_init_unchained();
__ERC20_init_unchained(_name, _symbol);
weth = _weth;
manager = _manager;
withheldLiquidity = 0;
}
function deposit(uint256 amount) external payable override whenNotPaused {
_deposit(msg.sender, msg.sender, amount, msg.value);
}
function depositFor(address account, uint256 amount) external payable override whenNotPaused {
_deposit(msg.sender, account, amount, msg.value);
}
function underlyer() external view override returns (address) {
return address(weth);
}
/// @dev References the WithdrawalInfo for how much the user is permitted to withdraw
/// @dev No withdrawal permitted unless currentCycle >= minCycle
/// @dev Decrements withheldLiquidity by the withdrawn amount
function withdraw(uint256 requestedAmount, bool asEth) external override whenNotPaused {
require(
requestedAmount <= requestedWithdrawals[msg.sender].amount,
"WITHDRAW_INSUFFICIENT_BALANCE"
);
require(requestedAmount > 0, "NO_WITHDRAWAL");
require(weth.balanceOf(address(this)) >= requestedAmount, "INSUFFICIENT_POOL_BALANCE");
require(
requestedWithdrawals[msg.sender].minCycle <= manager.getCurrentCycleIndex(),
"INVALID_CYCLE"
);
requestedWithdrawals[msg.sender].amount = requestedWithdrawals[msg.sender].amount.sub(
requestedAmount
);
if (requestedWithdrawals[msg.sender].amount == 0) {
delete requestedWithdrawals[msg.sender];
}
withheldLiquidity = withheldLiquidity.sub(requestedAmount);
_burn(msg.sender, requestedAmount);
if (asEth) {
weth.withdraw(requestedAmount);
msg.sender.sendValue(requestedAmount);
} else {
IERC20(weth).safeTransfer(msg.sender, requestedAmount);
}
}
/// @dev Adjusts the withheldLiquidity as necessary
/// @dev Updates the WithdrawalInfo for when a user can withdraw and for what requested amount
function requestWithdrawal(uint256 amount) external override {
require(amount > 0, "INVALID_AMOUNT");
require(amount <= balanceOf(msg.sender), "INSUFFICIENT_BALANCE");
//adjust withheld liquidity by removing the original withheld amount and adding the new amount
withheldLiquidity = withheldLiquidity.sub(requestedWithdrawals[msg.sender].amount).add(
amount
);
requestedWithdrawals[msg.sender].amount = amount;
if (manager.getRolloverStatus()) {
requestedWithdrawals[msg.sender].minCycle = manager.getCurrentCycleIndex().add(2);
} else {
requestedWithdrawals[msg.sender].minCycle = manager.getCurrentCycleIndex().add(1);
}
}
function preTransferAdjustWithheldLiquidity(address sender, uint256 amount) internal {
if (requestedWithdrawals[sender].amount > 0) {
//reduce requested withdraw amount by transferred amount;
uint256 newRequestedWithdrawl = requestedWithdrawals[sender].amount.sub(
Math.min(amount, requestedWithdrawals[sender].amount)
);
//subtract from global withheld liquidity (reduce) by removing the delta of (requestedAmount - newRequestedAmount)
withheldLiquidity = withheldLiquidity.sub(
requestedWithdrawals[msg.sender].amount.sub(newRequestedWithdrawl)
);
//update the requested withdraw for user
requestedWithdrawals[msg.sender].amount = newRequestedWithdrawl;
//if the withdraw request is 0, empty it out
if (requestedWithdrawals[msg.sender].amount == 0) {
delete requestedWithdrawals[msg.sender];
}
}
}
function approveManager(uint256 amount) public override onlyOwner {
uint256 currentAllowance = IERC20(weth).allowance(address(this), address(manager));
if (currentAllowance < amount) {
uint256 delta = amount.sub(currentAllowance);
IERC20(weth).safeIncreaseAllowance(address(manager), delta);
} else {
uint256 delta = currentAllowance.sub(amount);
IERC20(weth).safeDecreaseAllowance(address(manager), delta);
}
}
/// @dev Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer
function transfer(address recipient, uint256 amount) public override returns (bool) {
preTransferAdjustWithheldLiquidity(msg.sender, amount);
return super.transfer(recipient, amount);
}
/// @dev Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
preTransferAdjustWithheldLiquidity(sender, amount);
return super.transferFrom(sender, recipient, amount);
}
function pause() external override onlyOwner {
_pause();
}
function unpause() external override onlyOwner {
_unpause();
}
function _deposit(
address fromAccount,
address toAccount,
uint256 amount,
uint256 msgValue
) internal {
require(amount > 0, "INVALID_AMOUNT");
require(toAccount != address(0), "INVALID_ADDRESS");
_mint(toAccount, amount);
if (msgValue > 0) {
require(msgValue == amount, "AMT_VALUE_MISMATCH");
weth.deposit{value: amount}();
} else {
IERC20(weth).safeTransferFrom(fromAccount, address(this), amount);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "../interfaces/IWETH.sol";
import "../interfaces/IManager.sol";
/// @title Interface for Pool
/// @notice Allows users to deposit ERC-20 tokens to be deployed to market makers.
/// @notice Mints 1:1 fToken on deposit, represeting an IOU for the undelrying token that is freely transferable.
/// @notice Holders of fTokens earn rewards based on duration their tokens were deployed and the demand for that asset.
/// @notice Holders of fTokens can redeem for underlying asset after issuing requestWithdrawal and waiting for the next cycle.
interface ILiquidityEthPool {
struct WithdrawalInfo {
uint256 minCycle;
uint256 amount;
}
/// @notice Transfers amount of underlying token from user to this pool and mints fToken to the msg.sender.
/// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract.
/// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld.
function deposit(uint256 amount) external payable;
/// @notice Transfers amount of underlying token from user to this pool and mints fToken to the account.
/// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract.
/// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld.
function depositFor(address account, uint256 amount) external payable;
/// @notice Requests that the manager prepare funds for withdrawal next cycle
/// @notice Invoking this function when sender already has a currently pending request will overwrite that requested amount and reset the cycle timer
/// @param amount Amount of fTokens requested to be redeemed
function requestWithdrawal(uint256 amount) external;
function approveManager(uint256 amount) external;
/// @notice Sender must first invoke requestWithdrawal in a previous cycle
/// @notice This function will burn the fAsset and transfers underlying asset back to sender
/// @notice Will execute a partial withdrawal if either available liquidity or previously requested amount is insufficient
/// @param amount Amount of fTokens to redeem, value can be in excess of available tokens, operation will be reduced to maximum permissible
function withdraw(uint256 amount, bool asEth) external;
/// @return Reference to the underlying ERC-20 contract
function weth() external view returns (IWETH);
/// @return Reference to the underlying ERC-20 contract
function underlyer() external view returns (address);
/// @return Amount of liquidity that should not be deployed for market making (this liquidity will be used for completing requested withdrawals)
function withheldLiquidity() external view returns (uint256);
/// @notice Get withdraw requests for an account
/// @param account User account to check
/// @return minCycle Cycle - block number - that must be active before withdraw is allowed, amount Token amount requested
function requestedWithdrawals(address account) external view returns (uint256, uint256);
/// @notice Pause deposits on the pool. Withdraws still allowed
function pause() external;
/// @notice Unpause deposits on the pool.
function unpause() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface IWETH is IERC20Upgradeable {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/utils/SafeCast.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "../interfaces/ILiquidityPool.sol";
import "../interfaces/IDefiRound.sol";
import "../interfaces/IWETH.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
contract DefiRound is IDefiRound, Ownable {
using SafeMath for uint256;
using SafeCast for int256;
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using EnumerableSet for EnumerableSet.AddressSet;
// solhint-disable-next-line
address public immutable WETH;
address public override immutable treasury;
OversubscriptionRate public overSubscriptionRate;
mapping(address => uint256) public override totalSupply;
// account -> accountData
mapping(address => AccountData) private accountData;
mapping(address => RateData) private tokenRates;
//Token -> oracle, genesis
mapping(address => SupportedTokenData) private tokenSettings;
EnumerableSet.AddressSet private supportedTokens;
EnumerableSet.AddressSet private configuredTokenRates;
STAGES public override currentStage;
WhitelistSettings public whitelistSettings;
uint256 public lastLookExpiration = type(uint256).max;
uint256 private immutable maxTotalValue;
bool private stage1Locked;
constructor(
// solhint-disable-next-line
address _WETH,
address _treasury,
uint256 _maxTotalValue
) public {
require(_WETH != address(0), "INVALID_WETH");
require(_treasury != address(0), "INVALID_TREASURY");
require(_maxTotalValue > 0, "INVALID_MAXTOTAL");
WETH = _WETH;
treasury = _treasury;
currentStage = STAGES.STAGE_1;
maxTotalValue = _maxTotalValue;
}
function deposit(TokenData calldata tokenInfo, bytes32[] memory proof) external payable override {
require(currentStage == STAGES.STAGE_1, "DEPOSITS_NOT_ACCEPTED");
require(!stage1Locked, "DEPOSITS_LOCKED");
if (whitelistSettings.enabled) {
require(verifyDepositor(msg.sender, whitelistSettings.root, proof), "PROOF_INVALID");
}
TokenData memory data = tokenInfo;
address token = data.token;
uint256 tokenAmount = data.amount;
require(supportedTokens.contains(token), "UNSUPPORTED_TOKEN");
require(tokenAmount > 0, "INVALID_AMOUNT");
// Convert ETH to WETH if ETH is passed in, otherwise treat WETH as a regular ERC20
if (token == WETH && msg.value > 0) {
require(tokenAmount == msg.value, "INVALID_MSG_VALUE");
IWETH(WETH).deposit{value: tokenAmount}();
} else {
require(msg.value == 0, "NO_ETH");
}
AccountData storage tokenAccountData = accountData[msg.sender];
if (tokenAccountData.token == address(0)) {
tokenAccountData.token = token;
}
require(tokenAccountData.token == token, "SINGLE_ASSET_DEPOSITS");
tokenAccountData.initialDeposit = tokenAccountData.initialDeposit.add(tokenAmount);
tokenAccountData.currentBalance = tokenAccountData.currentBalance.add(tokenAmount);
require(tokenAccountData.currentBalance <= tokenSettings[token].maxLimit, "MAX_LIMIT_EXCEEDED");
// No need to transfer from msg.sender since is ETH was converted to WETH
if (!(token == WETH && msg.value > 0)) {
IERC20(token).safeTransferFrom(msg.sender, address(this), tokenAmount);
}
if(_totalValue() > maxTotalValue) {
stage1Locked = true;
}
emit Deposited(msg.sender, tokenInfo);
}
// solhint-disable-next-line no-empty-blocks
receive() external payable
{
require(msg.sender == WETH);
}
function withdraw(TokenData calldata tokenInfo, bool asETH) external override {
require(currentStage == STAGES.STAGE_2, "WITHDRAWS_NOT_ACCEPTED");
require(!_isLastLookComplete(), "WITHDRAWS_EXPIRED");
TokenData memory data = tokenInfo;
address token = data.token;
uint256 tokenAmount = data.amount;
require(supportedTokens.contains(token), "UNSUPPORTED_TOKEN");
require(tokenAmount > 0, "INVALID_AMOUNT");
AccountData storage tokenAccountData = accountData[msg.sender];
require(token == tokenAccountData.token, "INVALID_TOKEN");
tokenAccountData.currentBalance = tokenAccountData.currentBalance.sub(tokenAmount);
// set the data back in the mapping, otherwise updates are not saved
accountData[msg.sender] = tokenAccountData;
// Don't transfer WETH, WETH is converted to ETH and sent to the recipient
if (token == WETH && asETH) {
IWETH(WETH).withdraw(tokenAmount);
msg.sender.sendValue(tokenAmount);
} else {
IERC20(token).safeTransfer(msg.sender, tokenAmount);
}
emit Withdrawn(msg.sender, tokenInfo, asETH);
}
function configureWhitelist(WhitelistSettings memory settings) external override onlyOwner {
whitelistSettings = settings;
emit WhitelistConfigured(settings);
}
function addSupportedTokens(SupportedTokenData[] calldata tokensToSupport)
external
override
onlyOwner
{
uint256 tokensLength = tokensToSupport.length;
for (uint256 i = 0; i < tokensLength; i++) {
SupportedTokenData memory data = tokensToSupport[i];
require(supportedTokens.add(data.token), "TOKEN_EXISTS");
tokenSettings[data.token] = data;
}
emit SupportedTokensAdded(tokensToSupport);
}
function getSupportedTokens() external view override returns (address[] memory tokens) {
uint256 tokensLength = supportedTokens.length();
tokens = new address[](tokensLength);
for (uint256 i = 0; i < tokensLength; i++) {
tokens[i] = supportedTokens.at(i);
}
}
function publishRates(RateData[] calldata ratesData, OversubscriptionRate memory oversubRate, uint256 lastLookDuration) external override onlyOwner {
// check rates havent been published before
require(currentStage == STAGES.STAGE_1, "RATES_ALREADY_SET");
require(lastLookDuration > 0, "INVALID_DURATION");
require(oversubRate.overDenominator > 0, "INVALID_DENOMINATOR");
require(oversubRate.overNumerator > 0, "INVALID_NUMERATOR");
uint256 ratesLength = ratesData.length;
for (uint256 i = 0; i < ratesLength; i++) {
RateData memory data = ratesData[i];
require(data.numerator > 0, "INVALID_NUMERATOR");
require(data.denominator > 0, "INVALID_DENOMINATOR");
require(tokenRates[data.token].token == address(0), "RATE_ALREADY_SET");
require(configuredTokenRates.add(data.token), "ALREADY_CONFIGURED");
tokenRates[data.token] = data;
}
require(configuredTokenRates.length() == supportedTokens.length(), "MISSING_RATE");
// Stage only moves forward when prices are published
currentStage = STAGES.STAGE_2;
lastLookExpiration = block.number + lastLookDuration;
overSubscriptionRate = oversubRate;
emit RatesPublished(ratesData);
}
function getRates(address[] calldata tokens) external view override returns (RateData[] memory rates) {
uint256 tokensLength = tokens.length;
rates = new RateData[](tokensLength);
for (uint256 i = 0; i < tokensLength; i++) {
rates[i] = tokenRates[tokens[i]];
}
}
function getTokenValue(address token, uint256 balance) internal view returns (uint256 value) {
uint256 tokenDecimals = ERC20(token).decimals();
(, int256 tokenRate, , , ) = AggregatorV3Interface(tokenSettings[token].oracle).latestRoundData();
uint256 rate = tokenRate.toUint256();
value = (balance.mul(rate)).div(10**tokenDecimals); //Chainlink USD prices are always to 8
}
function totalValue() external view override returns (uint256) {
return _totalValue();
}
function _totalValue() internal view returns (uint256 value) {
uint256 tokensLength = supportedTokens.length();
for (uint256 i = 0; i < tokensLength; i++) {
address token = supportedTokens.at(i);
uint256 tokenBalance = IERC20(token).balanceOf(address(this));
value = value.add(getTokenValue(token, tokenBalance));
}
}
function accountBalance(address account) external view override returns (uint256 value) {
uint256 tokenBalance = accountData[account].currentBalance;
value = value.add(getTokenValue(accountData[account].token, tokenBalance));
}
function finalizeAssets(bool depositToGenesis) external override {
require(currentStage == STAGES.STAGE_3, "NOT_SYSTEM_FINAL");
AccountData storage data = accountData[msg.sender];
address token = data.token;
require(token != address(0), "NO_DATA");
( , uint256 ineffective, ) = _getRateAdjustedAmounts(data.currentBalance, token);
require(ineffective > 0, "NOTHING_TO_MOVE");
// zero out balance
data.currentBalance = 0;
accountData[msg.sender] = data;
if (depositToGenesis) {
address pool = tokenSettings[token].genesis;
uint256 currentAllowance = IERC20(token).allowance(address(this), pool);
if (currentAllowance < ineffective) {
IERC20(token).safeIncreaseAllowance(pool, ineffective.sub(currentAllowance));
}
ILiquidityPool(pool).depositFor(msg.sender, ineffective);
emit GenesisTransfer(msg.sender, ineffective);
} else {
// transfer ineffectiveTokenBalance back to user
IERC20(token).safeTransfer(msg.sender, ineffective);
}
emit AssetsFinalized(msg.sender, token, ineffective);
}
function getGenesisPools(address[] calldata tokens)
external
view
override
returns (address[] memory genesisAddresses)
{
uint256 tokensLength = tokens.length;
genesisAddresses = new address[](tokensLength);
for (uint256 i = 0; i < tokensLength; i++) {
require(supportedTokens.contains(tokens[i]), "TOKEN_UNSUPPORTED");
genesisAddresses[i] = tokenSettings[supportedTokens.at(i)].genesis;
}
}
function getTokenOracles(address[] calldata tokens)
external
view
override
returns (address[] memory oracleAddresses)
{
uint256 tokensLength = tokens.length;
oracleAddresses = new address[](tokensLength);
for (uint256 i = 0; i < tokensLength; i++) {
require(supportedTokens.contains(tokens[i]), "TOKEN_UNSUPPORTED");
oracleAddresses[i] = tokenSettings[tokens[i]].oracle;
}
}
function getAccountData(address account) external view override returns (AccountDataDetails[] memory data) {
uint256 supportedTokensLength = supportedTokens.length();
data = new AccountDataDetails[](supportedTokensLength);
for (uint256 i = 0; i < supportedTokensLength; i++) {
address token = supportedTokens.at(i);
AccountData memory accountTokenInfo = accountData[account];
if (currentStage >= STAGES.STAGE_2 && accountTokenInfo.token != address(0)) {
(uint256 effective, uint256 ineffective, uint256 actual) = _getRateAdjustedAmounts(accountTokenInfo.currentBalance, token);
AccountDataDetails memory details = AccountDataDetails(
token,
accountTokenInfo.initialDeposit,
accountTokenInfo.currentBalance,
effective,
ineffective,
actual
);
data[i] = details;
} else {
data[i] = AccountDataDetails(token, accountTokenInfo.initialDeposit, accountTokenInfo.currentBalance, 0, 0, 0);
}
}
}
function transferToTreasury() external override onlyOwner {
require(_isLastLookComplete(), "CURRENT_STAGE_INVALID");
require(currentStage == STAGES.STAGE_2, "ONLY_TRANSFER_ONCE");
uint256 supportedTokensLength = supportedTokens.length();
TokenData[] memory tokens = new TokenData[](supportedTokensLength);
for (uint256 i = 0; i < supportedTokensLength; i++) {
address token = supportedTokens.at(i);
uint256 balance = IERC20(token).balanceOf(address(this));
(uint256 effective, , ) = _getRateAdjustedAmounts(balance, token);
tokens[i].token = token;
tokens[i].amount = effective;
IERC20(token).safeTransfer(treasury, effective);
}
currentStage = STAGES.STAGE_3;
emit TreasuryTransfer(tokens);
}
function getRateAdjustedAmounts(uint256 balance, address token) external override view returns (uint256,uint256,uint256) {
return _getRateAdjustedAmounts(balance, token);
}
function getMaxTotalValue() external view override returns (uint256) {
return maxTotalValue;
}
function _getRateAdjustedAmounts(uint256 balance, address token) internal view returns (uint256,uint256,uint256) {
require(currentStage >= STAGES.STAGE_2, "RATES_NOT_PUBLISHED");
RateData memory rateInfo = tokenRates[token];
uint256 effectiveTokenBalance =
balance.mul(overSubscriptionRate.overNumerator).div(overSubscriptionRate.overDenominator);
uint256 ineffectiveTokenBalance =
balance.mul(overSubscriptionRate.overDenominator.sub(overSubscriptionRate.overNumerator))
.div(overSubscriptionRate.overDenominator);
uint256 actualReceived =
effectiveTokenBalance.mul(rateInfo.denominator).div(rateInfo.numerator);
return (effectiveTokenBalance, ineffectiveTokenBalance, actualReceived);
}
function verifyDepositor(address participant, bytes32 root, bytes32[] memory proof) internal pure returns (bool) {
bytes32 leaf = keccak256((abi.encodePacked((participant))));
return MerkleProof.verify(proof, root, leaf);
}
function _isLastLookComplete() internal view returns (bool) {
return block.number >= lastLookExpiration;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
interface IDefiRound {
enum STAGES {STAGE_1, STAGE_2, STAGE_3}
struct AccountData {
address token; // address of the allowed token deposited
uint256 initialDeposit; // initial amount deposited of the token
uint256 currentBalance; // current balance of the token that can be used to claim TOKE
}
struct AccountDataDetails {
address token; // address of the allowed token deposited
uint256 initialDeposit; // initial amount deposited of the token
uint256 currentBalance; // current balance of the token that can be used to claim TOKE
uint256 effectiveAmt; //Amount deposited that will be used towards TOKE
uint256 ineffectiveAmt; //Amount deposited that will be either refunded or go to farming
uint256 actualTokeReceived; //Amount of TOKE that will be received
}
struct TokenData {
address token;
uint256 amount;
}
struct SupportedTokenData {
address token;
address oracle;
address genesis;
uint256 maxLimit;
}
struct RateData {
address token;
uint256 numerator;
uint256 denominator;
}
struct OversubscriptionRate {
uint256 overNumerator;
uint256 overDenominator;
}
event Deposited(address depositor, TokenData tokenInfo);
event Withdrawn(address withdrawer, TokenData tokenInfo, bool asETH);
event SupportedTokensAdded(SupportedTokenData[] tokenData);
event RatesPublished(RateData[] ratesData);
event GenesisTransfer(address user, uint256 amountTransferred);
event AssetsFinalized(address claimer, address token, uint256 assetsMoved);
event WhitelistConfigured(WhitelistSettings settings);
event TreasuryTransfer(TokenData[] tokens);
struct TokenValues {
uint256 effectiveTokenValue;
uint256 ineffectiveTokenValue;
}
struct WhitelistSettings {
bool enabled;
bytes32 root;
}
/// @notice Enable or disable the whitelist
/// @param settings The root to use and whether to check the whitelist at all
function configureWhitelist(WhitelistSettings calldata settings) external;
/// @notice returns the current stage the contract is in
/// @return stage the current stage the round contract is in
function currentStage() external returns (STAGES stage);
/// @notice deposits tokens into the round contract
/// @param tokenData an array of token structs
function deposit(TokenData calldata tokenData, bytes32[] memory proof) external payable;
/// @notice total value held in the entire contract amongst all the assets
/// @return value the value of all assets held
function totalValue() external view returns (uint256 value);
/// @notice Current Max Total Value
function getMaxTotalValue() external view returns (uint256 value);
/// @notice returns the address of the treasury, when users claim this is where funds that are <= maxClaimableValue go
/// @return treasuryAddress address of the treasury
function treasury() external returns (address treasuryAddress);
/// @notice the total supply held for a given token
/// @param token the token to get the supply for
/// @return amount the total supply for a given token
function totalSupply(address token) external returns (uint256 amount);
/// @notice withdraws tokens from the round contract. only callable when round 2 starts
/// @param tokenData an array of token structs
/// @param asEth flag to determine if provided WETH, that it should be withdrawn as ETH
function withdraw(TokenData calldata tokenData, bool asEth) external;
// /// @notice adds tokens to support
// /// @param tokensToSupport an array of supported token structs
function addSupportedTokens(SupportedTokenData[] calldata tokensToSupport) external;
// /// @notice returns which tokens can be deposited
// /// @return tokens tokens that are supported for deposit
function getSupportedTokens() external view returns (address[] calldata tokens);
/// @notice the oracle that will be used to denote how much the amounts deposited are worth in USD
/// @param tokens an array of tokens
/// @return oracleAddresses the an array of oracles corresponding to supported tokens
function getTokenOracles(address[] calldata tokens)
external
view
returns (address[] calldata oracleAddresses);
/// @notice publishes rates for the tokens. Rates are always relative to 1 TOKE. Can only be called once within Stage 1
// prices can be published at any time
/// @param ratesData an array of rate info structs
function publishRates(
RateData[] calldata ratesData,
OversubscriptionRate memory overSubRate,
uint256 lastLookDuration
) external;
/// @notice return the published rates for the tokens
/// @param tokens an array of tokens to get rates for
/// @return rates an array of rates for the provided tokens
function getRates(address[] calldata tokens) external view returns (RateData[] calldata rates);
/// @notice determines the account value in USD amongst all the assets the user is invovled in
/// @param account the account to look up
/// @return value the value of the account in USD
function accountBalance(address account) external view returns (uint256 value);
/// @notice Moves excess assets to private farming or refunds them
/// @dev uses the publishedRates, selected tokens, and amounts to determine what amount of TOKE is claimed
/// @param depositToGenesis applies only if oversubscribedMultiplier < 1;
/// when true oversubscribed amount will deposit to genesis, else oversubscribed amount is sent back to user
function finalizeAssets(bool depositToGenesis) external;
//// @notice returns what gensis pool a supported token is mapped to
/// @param tokens array of addresses of supported tokens
/// @return genesisAddresses array of genesis pools corresponding to supported tokens
function getGenesisPools(address[] calldata tokens)
external
view
returns (address[] memory genesisAddresses);
/// @notice returns a list of AccountData for a provided account
/// @param account the address of the account
/// @return data an array of AccountData denoting what the status is for each of the tokens deposited (if any)
function getAccountData(address account)
external
view
returns (AccountDataDetails[] calldata data);
/// @notice Allows the owner to transfer all swapped assets to the treasury
/// @dev only callable by owner and if last look period is complete
function transferToTreasury() external;
/// @notice Given a balance, calculates how the the amount will be allocated between TOKE and Farming
/// @dev Only allowed at stage 3
/// @param balance balance to divy up
/// @param token token to pull the rates for
function getRateAdjustedAmounts(uint256 balance, address token)
external
view
returns (
uint256,
uint256,
uint256
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "../interfaces/ICoreEvent.sol";
import "../interfaces/ILiquidityPool.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
contract CoreEvent is Ownable, ICoreEvent {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
using EnumerableSet for EnumerableSet.AddressSet;
DurationInfo public durationInfo;
address public immutable treasuryAddress;
EnumerableSet.AddressSet private supportedTokenAddresses;
// token address -> SupportedTokenData
mapping(address => SupportedTokenData) public supportedTokens;
// user -> token -> AccountData
mapping(address => mapping(address => AccountData)) public accountData;
mapping(address => RateData) public tokenRates;
WhitelistSettings public whitelistSettings;
bool public stage1Locked;
modifier hasEnded() {
require(_hasEnded(), "TOO_EARLY");
_;
}
constructor(
address treasury,
SupportedTokenData[] memory tokensToSupport
) public {
treasuryAddress = treasury;
addSupportedTokens(tokensToSupport);
}
function configureWhitelist(WhitelistSettings memory settings) external override onlyOwner {
whitelistSettings = settings;
emit WhitelistConfigured(settings);
}
function setDuration(uint256 _blockDuration) external override onlyOwner {
require(durationInfo.startingBlock == 0, "ALREADY_STARTED");
durationInfo.startingBlock = block.number;
durationInfo.blockDuration = _blockDuration;
emit DurationSet(durationInfo);
}
function addSupportedTokens(SupportedTokenData[] memory tokensToSupport) public override onlyOwner {
require (tokensToSupport.length > 0, "NO_TOKENS");
for (uint256 i = 0; i < tokensToSupport.length; i++) {
require(
!supportedTokenAddresses.contains(tokensToSupport[i].token),
"DUPLICATE_TOKEN"
);
require(tokensToSupport[i].token != address(0), "ZERO_ADDRESS");
require(!tokensToSupport[i].systemFinalized, "FINALIZED_MUST_BE_FALSE");
supportedTokenAddresses.add(tokensToSupport[i].token);
supportedTokens[tokensToSupport[i].token] = tokensToSupport[i];
}
emit SupportedTokensAdded(tokensToSupport);
}
function deposit(TokenData[] calldata tokenData, bytes32[] calldata proof) external override {
require(durationInfo.startingBlock > 0, "NOT_STARTED");
require(!_hasEnded(), "RATES_LOCKED");
require(tokenData.length > 0, "NO_TOKENS");
if (whitelistSettings.enabled) {
require(verifyDepositor(msg.sender, whitelistSettings.root, proof), "PROOF_INVALID");
}
for (uint256 i = 0; i < tokenData.length; i++) {
uint256 amount = tokenData[i].amount;
require(amount > 0, "0_BALANCE");
address token = tokenData[i].token;
require(supportedTokenAddresses.contains(token), "NOT_SUPPORTED");
IERC20 erc20Token = IERC20(token);
AccountData storage data = accountData[msg.sender][token];
require(
data.depositedBalance.add(amount) <= supportedTokens[token].maxUserLimit,
"OVER_LIMIT"
);
data.depositedBalance = data.depositedBalance.add(amount);
data.token = token;
erc20Token.safeTransferFrom(msg.sender, address(this), amount);
}
emit Deposited(msg.sender, tokenData);
}
function withdraw(TokenData[] calldata tokenData) external override {
require(!_hasEnded(), "RATES_LOCKED");
require(tokenData.length > 0, "NO_TOKENS");
for (uint256 i = 0; i < tokenData.length; i++) {
uint256 amount = tokenData[i].amount;
require(amount > 0, "ZERO_BALANCE");
address token = tokenData[i].token;
IERC20 erc20Token = IERC20(token);
AccountData storage data = accountData[msg.sender][token];
require(data.token != address(0), "ZERO_ADDRESS");
require(amount <= data.depositedBalance, "INSUFFICIENT_FUNDS");
data.depositedBalance = data.depositedBalance.sub(amount);
if (data.depositedBalance == 0) {
delete accountData[msg.sender][token];
}
erc20Token.safeTransfer(msg.sender, amount);
}
emit Withdrawn(msg.sender, tokenData);
}
function increaseDuration(uint256 _blockDuration) external override onlyOwner {
require(durationInfo.startingBlock > 0, "NOT_STARTED");
require(_blockDuration > durationInfo.blockDuration, "INCREASE_ONLY");
require(!stage1Locked, "STAGE1_LOCKED");
durationInfo.blockDuration = _blockDuration;
emit DurationIncreased(durationInfo);
}
function setRates(RateData[] calldata rates) external override onlyOwner hasEnded {
//Rates are settable multiple times, but only until they are finalized.
//They are set to finalized by either performing the transferToTreasury
//Or, by marking them as no-swap tokens
//Users cannot begin their next set of actions before a token finalized.
uint256 length = rates.length;
for (uint256 i = 0; i < length; i++) {
RateData memory data = rates[i];
require(supportedTokenAddresses.contains(data.token), "UNSUPPORTED_ADDRESS");
require(!supportedTokens[data.token].systemFinalized, "ALREADY_FINALIZED");
if (data.tokeNumerator > 0) {
//We are allowing an address(0) pool, it means it was a winning reactor
//but there wasn't enough to enable private farming
require(data.tokeDenominator > 0, "INVALID_TOKE_DENOMINATOR");
require(data.overNumerator > 0, "INVALID_OVER_NUMERATOR");
require(data.overDenominator > 0, "INVALID_OVER_DENOMINATOR");
tokenRates[data.token] = data;
} else {
delete tokenRates[data.token];
}
}
stage1Locked = true;
emit RatesPublished(rates);
}
function transferToTreasury(address[] calldata tokens) external override onlyOwner hasEnded {
uint256 length = tokens.length;
TokenData[] memory transfers = new TokenData[](length);
for (uint256 i = 0; i < length; i++) {
address token = tokens[i];
require(tokenRates[token].tokeNumerator > 0, "NO_SWAP_TOKEN");
require(!supportedTokens[token].systemFinalized, "ALREADY_FINALIZED");
uint256 balance = IERC20(token).balanceOf(address(this));
(uint256 effective, , ) = getRateAdjustedAmounts(balance, token);
transfers[i].token = token;
transfers[i].amount = effective;
supportedTokens[token].systemFinalized = true;
IERC20(token).safeTransfer(treasuryAddress, effective);
}
emit TreasuryTransfer(transfers);
}
function setNoSwap(address[] calldata tokens) external override onlyOwner hasEnded {
uint256 length = tokens.length;
for (uint256 i = 0; i < length; i++) {
address token = tokens[i];
require(supportedTokenAddresses.contains(token), "UNSUPPORTED_ADDRESS");
require(tokenRates[token].tokeNumerator == 0, "ALREADY_SET_TO_SWAP");
require(!supportedTokens[token].systemFinalized, "ALREADY_FINALIZED");
supportedTokens[token].systemFinalized = true;
}
stage1Locked = true;
emit SetNoSwap(tokens);
}
function finalize(TokenFarming[] calldata tokens) external override hasEnded {
require(tokens.length > 0, "NO_TOKENS");
uint256 length = tokens.length;
FinalizedAccountData[] memory results = new FinalizedAccountData[](length);
for(uint256 i = 0; i < length; i++) {
TokenFarming calldata farm = tokens[i];
AccountData storage account = accountData[msg.sender][farm.token];
require(!account.finalized, "ALREADY_FINALIZED");
require(farm.token != address(0), "ZERO_ADDRESS");
require(supportedTokens[farm.token].systemFinalized, "NOT_SYSTEM_FINALIZED");
require(account.depositedBalance > 0, "INSUFFICIENT_FUNDS");
RateData storage rate = tokenRates[farm.token];
uint256 amtToTransfer = 0;
if (rate.tokeNumerator > 0) {
//We have set a rate, which means its a winning reactor
//which means only the ineffective amount, the amount
//not spent on TOKE, can leave the contract.
//Leaving to either the farm or back to the user
//In the event there is no farming, an oversubscription rate of 1/1
//will be provided for the token. That will ensure the ineffective
//amount is 0 and caught by the below require() as only assets with
//an oversubscription can be moved
(, uint256 ineffectiveAmt, ) = getRateAdjustedAmounts(account.depositedBalance, farm.token);
amtToTransfer = ineffectiveAmt;
} else {
amtToTransfer = account.depositedBalance;
}
require(amtToTransfer > 0, "NOTHING_TO_MOVE");
account.finalized = true;
if (farm.sendToFarming) {
require(rate.pool != address(0), "NO_FARMING");
uint256 currentAllowance = IERC20(farm.token).allowance(address(this), rate.pool);
if (currentAllowance < amtToTransfer) {
IERC20(farm.token).safeIncreaseAllowance(rate.pool, amtToTransfer.sub(currentAllowance));
}
ILiquidityPool(rate.pool).depositFor(msg.sender, amtToTransfer);
results[i] = FinalizedAccountData({
token: farm.token,
transferredToFarm: amtToTransfer,
refunded: 0
});
} else {
IERC20(farm.token).safeTransfer(msg.sender, amtToTransfer);
results[i] = FinalizedAccountData({
token: farm.token,
transferredToFarm: 0,
refunded: amtToTransfer
});
}
}
emit AssetsFinalized(msg.sender, results);
}
function getRateAdjustedAmounts(uint256 balance, address token) public override view returns (uint256 effectiveAmt, uint256 ineffectiveAmt, uint256 actualReceived) {
RateData memory rateInfo = tokenRates[token];
uint256 effectiveTokenBalance =
balance.mul(rateInfo.overNumerator).div(rateInfo.overDenominator);
uint256 ineffectiveTokenBalance =
balance.mul(rateInfo.overDenominator.sub(rateInfo.overNumerator))
.div(rateInfo.overDenominator);
uint256 actual =
effectiveTokenBalance.mul(rateInfo.tokeDenominator).div(rateInfo.tokeNumerator);
return (effectiveTokenBalance, ineffectiveTokenBalance, actual);
}
function getRates() external override view returns (RateData[] memory rates) {
uint256 length = supportedTokenAddresses.length();
rates = new RateData[](length);
for (uint256 i = 0; i < length; i++) {
address token = supportedTokenAddresses.at(i);
rates[i] = tokenRates[token];
}
}
function getAccountData(address account) external view override returns (AccountData[] memory data) {
uint256 length = supportedTokenAddresses.length();
data = new AccountData[](length);
for(uint256 i = 0; i < length; i++) {
address token = supportedTokenAddresses.at(i);
data[i] = accountData[account][token];
data[i].token = token;
}
}
function getSupportedTokens() external view override returns (SupportedTokenData[] memory supportedTokensArray) {
uint256 supportedTokensLength = supportedTokenAddresses.length();
supportedTokensArray = new SupportedTokenData[](supportedTokensLength);
for (uint256 i = 0; i < supportedTokensLength; i++) {
supportedTokensArray[i] = supportedTokens[supportedTokenAddresses.at(i)];
}
return supportedTokensArray;
}
function _hasEnded() private view returns (bool) {
return durationInfo.startingBlock > 0 && block.number >= durationInfo.blockDuration + durationInfo.startingBlock;
}
function verifyDepositor(address participant, bytes32 root, bytes32[] memory proof) internal pure returns (bool) {
bytes32 leaf = keccak256((abi.encodePacked((participant))));
return MerkleProof.verify(proof, root, leaf);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
interface ICoreEvent {
struct SupportedTokenData {
address token;
uint256 maxUserLimit;
bool systemFinalized; // Whether or not the system is done setting rates, doing transfers, for this token
}
struct DurationInfo {
uint256 startingBlock;
uint256 blockDuration; // Block duration of the deposit/withdraw stage
}
struct RateData {
address token;
uint256 tokeNumerator;
uint256 tokeDenominator;
uint256 overNumerator;
uint256 overDenominator;
address pool;
}
struct TokenData {
address token;
uint256 amount;
}
struct AccountData {
address token; // Address of the allowed token deposited
uint256 depositedBalance;
bool finalized; // Has the user either taken their refund or sent to farming. Will not be set on swapped but undersubscribed tokens.
}
struct FinalizedAccountData {
address token;
uint256 transferredToFarm;
uint256 refunded;
}
struct TokenFarming {
address token; // address of the allowed token deposited
bool sendToFarming; // Refund is default
}
struct WhitelistSettings {
bool enabled;
bytes32 root;
}
event SupportedTokensAdded(SupportedTokenData[] tokenData);
event TreasurySet(address treasury);
event DurationSet(DurationInfo duration);
event DurationIncreased(DurationInfo duration);
event Deposited(address depositor, TokenData[] tokenInfo);
event Withdrawn(address withdrawer, TokenData[] tokenInfo);
event RatesPublished(RateData[] ratesData);
event AssetsFinalized(address user, FinalizedAccountData[] data);
event TreasuryTransfer(TokenData[] tokens);
event WhitelistConfigured(WhitelistSettings settings);
event SetNoSwap(address[] tokens);
//==========================================
// Initial setup operations
//==========================================
/// @notice Enable or disable the whitelist
/// @param settings The root to use and whether to check the whitelist at all
function configureWhitelist(WhitelistSettings memory settings) external;
/// @notice defines the length in blocks the round will run for
/// @notice round is started via this call and it is only callable one time
/// @param blockDuration Duration in blocks the deposit/withdraw portion will run for
function setDuration(uint256 blockDuration) external;
/// @notice adds tokens to support
/// @param tokensToSupport an array of supported token structs
function addSupportedTokens(SupportedTokenData[] memory tokensToSupport) external;
//==========================================
// Stage 1 timeframe operations
//==========================================
/// @notice deposits tokens into the round contract
/// @param tokenData an array of token structs
/// @param proof Merkle proof for the user. Only required if whitelistSettings.enabled
function deposit(TokenData[] calldata tokenData, bytes32[] calldata proof) external;
/// @notice withdraws tokens from the round contract
/// @param tokenData an array of token structs
function withdraw(TokenData[] calldata tokenData) external;
/// @notice extends the deposit/withdraw stage
/// @notice Only extendable if no tokens have been finalized and no rates set
/// @param blockDuration Duration in blocks the deposit/withdraw portion will run for. Must be greater than original
function increaseDuration(uint256 blockDuration) external;
//==========================================
// Stage 1 -> 2 transition operations
//==========================================
/// @notice once the expected duration has passed, publish the Toke and over subscription rates
/// @notice tokens which do not have a published rate will have their users forced to withdraw all funds
/// @dev pass a tokeNumerator of 0 to delete a set rate
/// @dev Cannot be called for a token once transferToTreasury/setNoSwap has been called for that token
function setRates(RateData[] calldata rates) external;
/// @notice Allows the owner to transfer the effective balance of a token based on the set rate to the treasury
/// @dev only callable by owner and if rates have been set
/// @dev is only callable one time for a token
function transferToTreasury(address[] calldata tokens) external;
/// @notice Marks a token as finalized but not swapping
/// @dev complement to transferToTreasury which is for tokens that will be swapped, this one for ones that won't
function setNoSwap(address[] calldata tokens) external;
//==========================================
// Stage 2 operations
//==========================================
/// @notice Once rates have been published, and the token finalized via transferToTreasury/setNoSwap, either refunds or sends to private farming
/// @param tokens an array of tokens and whether to send them to private farming. False on farming will send back to user.
function finalize(TokenFarming[] calldata tokens) external;
//==========================================
// View operations
//==========================================
/// @notice Breaks down the balance according to the published rates
/// @dev only callable after rates have been set
function getRateAdjustedAmounts(uint256 balance, address token) external view returns (uint256 effectiveAmt, uint256 ineffectiveAmt, uint256 actualReceived);
/// @notice return the published rates for the tokens
/// @return rates an array of rates for the provided tokens
function getRates() external view returns (RateData[] memory rates);
/// @notice returns a list of AccountData for a provided account
/// @param account the address of the account
/// @return data an array of AccountData denoting what the status is for each of the tokens deposited (if any)
function getAccountData(address account) external view returns (AccountData[] calldata data);
/// @notice get all tokens currently supported by the contract
/// @return supportedTokensArray an array of supported token structs
function getSupportedTokens() external view returns (SupportedTokenData[] memory supportedTokensArray);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ERC20.sol";
import "../../utils/Pausable.sol";
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20Pausable is ERC20, Pausable {
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract Toke is ERC20Pausable, Ownable {
uint256 private constant SUPPLY = 100_000_000e18;
constructor() public ERC20("Tokemak", "TOKE") {
_mint(msg.sender, SUPPLY); // 100M
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
contract Rewards is Ownable {
using SafeMath for uint256;
using ECDSA for bytes32;
using SafeERC20 for IERC20;
mapping(address => uint256) public claimedAmounts;
event SignerSet(address newSigner);
event Claimed(uint256 cycle, address recipient, uint256 amount);
struct EIP712Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
}
struct Recipient {
uint256 chainId;
uint256 cycle;
address wallet;
uint256 amount;
}
bytes32 private constant EIP712_DOMAIN_TYPEHASH =
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
bytes32 private constant RECIPIENT_TYPEHASH =
keccak256("Recipient(uint256 chainId,uint256 cycle,address wallet,uint256 amount)");
bytes32 private immutable domainSeparator;
IERC20 public immutable tokeToken;
address public rewardsSigner;
constructor(IERC20 token, address signerAddress) public {
require(address(token) != address(0), "Invalid TOKE Address");
require(signerAddress != address(0), "Invalid Signer Address");
tokeToken = token;
rewardsSigner = signerAddress;
domainSeparator = _hashDomain(
EIP712Domain({
name: "TOKE Distribution",
version: "1",
chainId: _getChainID(),
verifyingContract: address(this)
})
);
}
function _hashDomain(EIP712Domain memory eip712Domain) private pure returns (bytes32) {
return
keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(eip712Domain.name)),
keccak256(bytes(eip712Domain.version)),
eip712Domain.chainId,
eip712Domain.verifyingContract
)
);
}
function _hashRecipient(Recipient memory recipient) private pure returns (bytes32) {
return
keccak256(
abi.encode(
RECIPIENT_TYPEHASH,
recipient.chainId,
recipient.cycle,
recipient.wallet,
recipient.amount
)
);
}
function _hash(Recipient memory recipient) private view returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, _hashRecipient(recipient)));
}
function _getChainID() private pure returns (uint256) {
uint256 id;
// solhint-disable-next-line no-inline-assembly
assembly {
id := chainid()
}
return id;
}
function setSigner(address newSigner) external onlyOwner {
require(newSigner != address(0), "Invalid Signer Address");
rewardsSigner = newSigner;
}
function getClaimableAmount(
Recipient calldata recipient
) external view returns (uint256) {
return recipient.amount.sub(claimedAmounts[recipient.wallet]);
}
function claim(
Recipient calldata recipient,
uint8 v,
bytes32 r,
bytes32 s // bytes calldata signature
) external {
address signatureSigner = _hash(recipient).recover(v, r, s);
require(signatureSigner == rewardsSigner, "Invalid Signature");
require(recipient.chainId == _getChainID(), "Invalid chainId");
require(recipient.wallet == msg.sender, "Sender wallet Mismatch");
uint256 claimableAmount = recipient.amount.sub(claimedAmounts[recipient.wallet]);
require(claimableAmount > 0, "Invalid claimable amount");
require(tokeToken.balanceOf(address(this)) >= claimableAmount, "Insufficient Funds");
claimedAmounts[recipient.wallet] = claimedAmounts[recipient.wallet].add(claimableAmount);
tokeToken.safeTransfer(recipient.wallet, claimableAmount);
emit Claimed(recipient.cycle, recipient.wallet, claimableAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../interfaces/IStaking.sol";
/// @title Tokemak Redeem Contract
/// @notice Converts PreToke to Toke
/// @dev Can only be used when fromToken has been unpaused
contract Redeem is Ownable {
using SafeERC20 for IERC20;
address public immutable fromToken;
address public immutable toToken;
address public immutable stakingContract;
uint256 public immutable expirationBlock;
uint256 public immutable stakingSchedule;
/// @notice Redeem Constructor
/// @dev approves max uint256 on creation for the toToken against the staking contract
/// @param _fromToken the token users will convert from
/// @param _toToken the token users will convert to
/// @param _stakingContract the staking contract
/// @param _expirationBlock a block number at which the owner can withdraw the full balance of toToken
constructor(
address _fromToken,
address _toToken,
address _stakingContract,
uint256 _expirationBlock,
uint256 _stakingSchedule
) public {
require(_fromToken != address(0), "INVALID_FROMTOKEN");
require(_toToken != address(0), "INVALID_TOTOKEN");
require(_stakingContract != address(0), "INVALID_STAKING");
fromToken = _fromToken;
toToken = _toToken;
stakingContract = _stakingContract;
expirationBlock = _expirationBlock;
stakingSchedule = _stakingSchedule;
//Approve staking contract for toToken to allow for staking within convert()
IERC20(_toToken).safeApprove(_stakingContract, type(uint256).max);
}
/// @notice Allows a holder of fromToken to convert into toToken and simultaneously stake within the stakingContract
/// @dev a user must approve this contract in order for it to burnFrom()
function convert() external {
uint256 fromBal = IERC20(fromToken).balanceOf(msg.sender);
require(fromBal > 0, "INSUFFICIENT_BALANCE");
ERC20Burnable(fromToken).burnFrom(msg.sender, fromBal);
IStaking(stakingContract).depositFor(msg.sender, fromBal, stakingSchedule);
}
/// @notice Allows the claim on the toToken balance after the expiration has passed
/// @dev callable only by owner
function recoupRemaining() external onlyOwner {
require(block.number >= expirationBlock, "EXPIRATION_NOT_PASSED");
uint256 bal = IERC20(toToken).balanceOf(address(this));
IERC20(toToken).safeTransfer(msg.sender, bal);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./ERC20.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
using SafeMath for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../access/AccessControl.sol";
import "../utils/Context.sol";
import "../token/ERC20/ERC20.sol";
import "../token/ERC20/ERC20Burnable.sol";
import "../token/ERC20/ERC20Pausable.sol";
/**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract ERC20PresetMinterPauser is Context, AccessControl, ERC20Burnable, ERC20Pausable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
constructor(string memory name, string memory symbol) public ERC20(name, symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_mint(to, amount);
}
/**
* @dev 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();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "@openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol";
// solhint-disable-next-line
contract PreToke is ERC20PresetMinterPauser("PreToke", "PTOKE") {
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
// We import the contract so truffle compiles it, and we have the ABI
// available when working from truffle console.
import "@gnosis.pm/mock-contract/contracts/MockContract.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2ERC20.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Router02.sol" as ISushiswapV2Router;
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol" as ISushiswapV2Factory;
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2ERC20.sol" as ISushiswapV2ERC20;
pragma solidity ^0.6.0;
interface MockInterface {
/**
* @dev After calling this method, the mock will return `response` when it is called
* with any calldata that is not mocked more specifically below
* (e.g. using givenMethodReturn).
* @param response ABI encoded response that will be returned if method is invoked
*/
function givenAnyReturn(bytes calldata response) external;
function givenAnyReturnBool(bool response) external;
function givenAnyReturnUint(uint response) external;
function givenAnyReturnAddress(address response) external;
function givenAnyRevert() external;
function givenAnyRevertWithMessage(string calldata message) external;
function givenAnyRunOutOfGas() external;
/**
* @dev After calling this method, the mock will return `response` when the given
* methodId is called regardless of arguments. If the methodId and arguments
* are mocked more specifically (using `givenMethodAndArguments`) the latter
* will take precedence.
* @param method ABI encoded methodId. It is valid to pass full calldata (including arguments). The mock will extract the methodId from it
* @param response ABI encoded response that will be returned if method is invoked
*/
function givenMethodReturn(bytes calldata method, bytes calldata response) external;
function givenMethodReturnBool(bytes calldata method, bool response) external;
function givenMethodReturnUint(bytes calldata method, uint response) external;
function givenMethodReturnAddress(bytes calldata method, address response) external;
function givenMethodRevert(bytes calldata method) external;
function givenMethodRevertWithMessage(bytes calldata method, string calldata message) external;
function givenMethodRunOutOfGas(bytes calldata method) external;
/**
* @dev After calling this method, the mock will return `response` when the given
* methodId is called with matching arguments. These exact calldataMocks will take
* precedence over all other calldataMocks.
* @param call ABI encoded calldata (methodId and arguments)
* @param response ABI encoded response that will be returned if contract is invoked with calldata
*/
function givenCalldataReturn(bytes calldata call, bytes calldata response) external;
function givenCalldataReturnBool(bytes calldata call, bool response) external;
function givenCalldataReturnUint(bytes calldata call, uint response) external;
function givenCalldataReturnAddress(bytes calldata call, address response) external;
function givenCalldataRevert(bytes calldata call) external;
function givenCalldataRevertWithMessage(bytes calldata call, string calldata message) external;
function givenCalldataRunOutOfGas(bytes calldata call) external;
/**
* @dev Returns the number of times anything has been called on this mock since last reset
*/
function invocationCount() external returns (uint);
/**
* @dev Returns the number of times the given method has been called on this mock since last reset
* @param method ABI encoded methodId. It is valid to pass full calldata (including arguments). The mock will extract the methodId from it
*/
function invocationCountForMethod(bytes calldata method) external returns (uint);
/**
* @dev Returns the number of times this mock has been called with the exact calldata since last reset.
* @param call ABI encoded calldata (methodId and arguments)
*/
function invocationCountForCalldata(bytes calldata call) external returns (uint);
/**
* @dev Resets all mocked methods and invocation counts.
*/
function reset() external;
}
/**
* Implementation of the MockInterface.
*/
contract MockContract is MockInterface {
enum MockType { Return, Revert, OutOfGas }
bytes32 public constant MOCKS_LIST_START = hex"01";
bytes public constant MOCKS_LIST_END = "0xff";
bytes32 public constant MOCKS_LIST_END_HASH = keccak256(MOCKS_LIST_END);
bytes4 public constant SENTINEL_ANY_MOCKS = hex"01";
bytes public constant DEFAULT_FALLBACK_VALUE = abi.encode(false);
// A linked list allows easy iteration and inclusion checks
mapping(bytes32 => bytes) calldataMocks;
mapping(bytes => MockType) calldataMockTypes;
mapping(bytes => bytes) calldataExpectations;
mapping(bytes => string) calldataRevertMessage;
mapping(bytes32 => uint) calldataInvocations;
mapping(bytes4 => bytes4) methodIdMocks;
mapping(bytes4 => MockType) methodIdMockTypes;
mapping(bytes4 => bytes) methodIdExpectations;
mapping(bytes4 => string) methodIdRevertMessages;
mapping(bytes32 => uint) methodIdInvocations;
MockType fallbackMockType;
bytes fallbackExpectation = DEFAULT_FALLBACK_VALUE;
string fallbackRevertMessage;
uint invocations;
uint resetCount;
constructor() public {
calldataMocks[MOCKS_LIST_START] = MOCKS_LIST_END;
methodIdMocks[SENTINEL_ANY_MOCKS] = SENTINEL_ANY_MOCKS;
}
function trackCalldataMock(bytes memory call) private {
bytes32 callHash = keccak256(call);
if (calldataMocks[callHash].length == 0) {
calldataMocks[callHash] = calldataMocks[MOCKS_LIST_START];
calldataMocks[MOCKS_LIST_START] = call;
}
}
function trackMethodIdMock(bytes4 methodId) private {
if (methodIdMocks[methodId] == 0x0) {
methodIdMocks[methodId] = methodIdMocks[SENTINEL_ANY_MOCKS];
methodIdMocks[SENTINEL_ANY_MOCKS] = methodId;
}
}
function _givenAnyReturn(bytes memory response) internal {
fallbackMockType = MockType.Return;
fallbackExpectation = response;
}
function givenAnyReturn(bytes calldata response) override external {
_givenAnyReturn(response);
}
function givenAnyReturnBool(bool response) override external {
uint flag = response ? 1 : 0;
_givenAnyReturn(uintToBytes(flag));
}
function givenAnyReturnUint(uint response) override external {
_givenAnyReturn(uintToBytes(response));
}
function givenAnyReturnAddress(address response) override external {
_givenAnyReturn(uintToBytes(uint(response)));
}
function givenAnyRevert() override external {
fallbackMockType = MockType.Revert;
fallbackRevertMessage = "";
}
function givenAnyRevertWithMessage(string calldata message) override external {
fallbackMockType = MockType.Revert;
fallbackRevertMessage = message;
}
function givenAnyRunOutOfGas() override external {
fallbackMockType = MockType.OutOfGas;
}
function _givenCalldataReturn(bytes memory call, bytes memory response) private {
calldataMockTypes[call] = MockType.Return;
calldataExpectations[call] = response;
trackCalldataMock(call);
}
function givenCalldataReturn(bytes calldata call, bytes calldata response) override external {
_givenCalldataReturn(call, response);
}
function givenCalldataReturnBool(bytes calldata call, bool response) override external {
uint flag = response ? 1 : 0;
_givenCalldataReturn(call, uintToBytes(flag));
}
function givenCalldataReturnUint(bytes calldata call, uint response) override external {
_givenCalldataReturn(call, uintToBytes(response));
}
function givenCalldataReturnAddress(bytes calldata call, address response) override external {
_givenCalldataReturn(call, uintToBytes(uint(response)));
}
function _givenMethodReturn(bytes memory call, bytes memory response) private {
bytes4 method = bytesToBytes4(call);
methodIdMockTypes[method] = MockType.Return;
methodIdExpectations[method] = response;
trackMethodIdMock(method);
}
function givenMethodReturn(bytes calldata call, bytes calldata response) override external {
_givenMethodReturn(call, response);
}
function givenMethodReturnBool(bytes calldata call, bool response) override external {
uint flag = response ? 1 : 0;
_givenMethodReturn(call, uintToBytes(flag));
}
function givenMethodReturnUint(bytes calldata call, uint response) override external {
_givenMethodReturn(call, uintToBytes(response));
}
function givenMethodReturnAddress(bytes calldata call, address response) override external {
_givenMethodReturn(call, uintToBytes(uint(response)));
}
function givenCalldataRevert(bytes calldata call) override external {
calldataMockTypes[call] = MockType.Revert;
calldataRevertMessage[call] = "";
trackCalldataMock(call);
}
function givenMethodRevert(bytes calldata call) override external {
bytes4 method = bytesToBytes4(call);
methodIdMockTypes[method] = MockType.Revert;
trackMethodIdMock(method);
}
function givenCalldataRevertWithMessage(bytes calldata call, string calldata message) override external {
calldataMockTypes[call] = MockType.Revert;
calldataRevertMessage[call] = message;
trackCalldataMock(call);
}
function givenMethodRevertWithMessage(bytes calldata call, string calldata message) override external {
bytes4 method = bytesToBytes4(call);
methodIdMockTypes[method] = MockType.Revert;
methodIdRevertMessages[method] = message;
trackMethodIdMock(method);
}
function givenCalldataRunOutOfGas(bytes calldata call) override external {
calldataMockTypes[call] = MockType.OutOfGas;
trackCalldataMock(call);
}
function givenMethodRunOutOfGas(bytes calldata call) override external {
bytes4 method = bytesToBytes4(call);
methodIdMockTypes[method] = MockType.OutOfGas;
trackMethodIdMock(method);
}
function invocationCount() override external returns (uint) {
return invocations;
}
function invocationCountForMethod(bytes calldata call) override external returns (uint) {
bytes4 method = bytesToBytes4(call);
return methodIdInvocations[keccak256(abi.encodePacked(resetCount, method))];
}
function invocationCountForCalldata(bytes calldata call) override external returns (uint) {
return calldataInvocations[keccak256(abi.encodePacked(resetCount, call))];
}
function reset() override external {
// Reset all exact calldataMocks
bytes memory nextMock = calldataMocks[MOCKS_LIST_START];
bytes32 mockHash = keccak256(nextMock);
// We cannot compary bytes
while(mockHash != MOCKS_LIST_END_HASH) {
// Reset all mock maps
calldataMockTypes[nextMock] = MockType.Return;
calldataExpectations[nextMock] = hex"";
calldataRevertMessage[nextMock] = "";
// Set next mock to remove
nextMock = calldataMocks[mockHash];
// Remove from linked list
calldataMocks[mockHash] = "";
// Update mock hash
mockHash = keccak256(nextMock);
}
// Clear list
calldataMocks[MOCKS_LIST_START] = MOCKS_LIST_END;
// Reset all any calldataMocks
bytes4 nextAnyMock = methodIdMocks[SENTINEL_ANY_MOCKS];
while(nextAnyMock != SENTINEL_ANY_MOCKS) {
bytes4 currentAnyMock = nextAnyMock;
methodIdMockTypes[currentAnyMock] = MockType.Return;
methodIdExpectations[currentAnyMock] = hex"";
methodIdRevertMessages[currentAnyMock] = "";
nextAnyMock = methodIdMocks[currentAnyMock];
// Remove from linked list
methodIdMocks[currentAnyMock] = 0x0;
}
// Clear list
methodIdMocks[SENTINEL_ANY_MOCKS] = SENTINEL_ANY_MOCKS;
fallbackExpectation = DEFAULT_FALLBACK_VALUE;
fallbackMockType = MockType.Return;
invocations = 0;
resetCount += 1;
}
function useAllGas() private {
while(true) {
bool s;
assembly {
//expensive call to EC multiply contract
s := call(sub(gas(), 2000), 6, 0, 0x0, 0xc0, 0x0, 0x60)
}
}
}
function bytesToBytes4(bytes memory b) private pure returns (bytes4) {
bytes4 out;
for (uint i = 0; i < 4; i++) {
out |= bytes4(b[i] & 0xFF) >> (i * 8);
}
return out;
}
function uintToBytes(uint256 x) private pure returns (bytes memory b) {
b = new bytes(32);
assembly { mstore(add(b, 32), x) }
}
function updateInvocationCount(bytes4 methodId, bytes memory originalMsgData) public {
require(msg.sender == address(this), "Can only be called from the contract itself");
invocations += 1;
methodIdInvocations[keccak256(abi.encodePacked(resetCount, methodId))] += 1;
calldataInvocations[keccak256(abi.encodePacked(resetCount, originalMsgData))] += 1;
}
fallback () payable external {
bytes4 methodId;
assembly {
methodId := calldataload(0)
}
// First, check exact matching overrides
if (calldataMockTypes[msg.data] == MockType.Revert) {
revert(calldataRevertMessage[msg.data]);
}
if (calldataMockTypes[msg.data] == MockType.OutOfGas) {
useAllGas();
}
bytes memory result = calldataExpectations[msg.data];
// Then check method Id overrides
if (result.length == 0) {
if (methodIdMockTypes[methodId] == MockType.Revert) {
revert(methodIdRevertMessages[methodId]);
}
if (methodIdMockTypes[methodId] == MockType.OutOfGas) {
useAllGas();
}
result = methodIdExpectations[methodId];
}
// Last, use the fallback override
if (result.length == 0) {
if (fallbackMockType == MockType.Revert) {
revert(fallbackRevertMessage);
}
if (fallbackMockType == MockType.OutOfGas) {
useAllGas();
}
result = fallbackExpectation;
}
// Record invocation as separate call so we don't rollback in case we are called with STATICCALL
(, bytes memory r) = address(this).call{gas: 100000}(abi.encodeWithSignature("updateInvocationCount(bytes4,bytes)", methodId, msg.data));
assert(r.length == 0);
assembly {
return(add(0x20, result), mload(result))
}
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
pragma solidity >=0.5.0;
interface IUniswapV2ERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function migrator() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function setMigrator(address) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IUniswapV2ERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Router02.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
contract SushiswapController {
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using SafeMath for uint256;
// solhint-disable-next-line var-name-mixedcase
IUniswapV2Router02 public immutable SUSHISWAP_ROUTER;
// solhint-disable-next-line var-name-mixedcase
IUniswapV2Factory public immutable SUSHISWAP_FACTORY;
constructor(IUniswapV2Router02 router, IUniswapV2Factory factory) public {
require(address(router) != address(0), "INVALID_ROUTER");
require(address(factory) != address(0), "INVALID_FACTORY");
SUSHISWAP_ROUTER = router;
SUSHISWAP_FACTORY = factory;
}
function deploy(bytes calldata data) external {
(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) = abi.decode(
data,
(address, address, uint256, uint256, uint256, uint256, address, uint256)
);
_approve(IERC20(tokenA), amountADesired);
_approve(IERC20(tokenB), amountBDesired);
//(uint256 amountA, uint256 amountB, uint256 liquidity) =
SUSHISWAP_ROUTER.addLiquidity(
tokenA,
tokenB,
amountADesired,
amountBDesired,
amountAMin,
amountBMin,
to,
deadline
);
// TODO: perform checks on amountA, amountB, liquidity
}
function withdraw(bytes calldata data) external {
(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) = abi.decode(data, (address, address, uint256, uint256, uint256, address, uint256));
address pair = SUSHISWAP_FACTORY.getPair(tokenA, tokenB);
require(pair != address(0), "pair doesn't exist");
_approve(IERC20(pair), liquidity);
//(uint256 amountA, uint256 amountB) =
SUSHISWAP_ROUTER.removeLiquidity(
tokenA,
tokenB,
liquidity,
amountAMin,
amountBMin,
to,
deadline
);
//TODO: perform checks on amountA and amountB
}
function _approve(IERC20 token, uint256 amount) internal {
uint256 currentAllowance = token.allowance(address(this), address(SUSHISWAP_ROUTER));
if (currentAllowance < amount) {
token.safeIncreaseAllowance(
address(SUSHISWAP_ROUTER),
type(uint256).max.sub(currentAllowance)
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
contract UniswapController {
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using SafeMath for uint256;
// solhint-disable-next-line var-name-mixedcase
IUniswapV2Router02 public immutable UNISWAP_ROUTER;
// solhint-disable-next-line var-name-mixedcase
IUniswapV2Factory public immutable UNISWAP_FACTORY;
constructor(IUniswapV2Router02 router, IUniswapV2Factory factory) public {
require(address(router) != address(0), "INVALID_ROUTER");
require(address(factory) != address(0), "INVALID_FACTORY");
UNISWAP_ROUTER = router;
UNISWAP_FACTORY = factory;
}
function deploy(bytes calldata data) external {
(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) = abi.decode(
data,
(address, address, uint256, uint256, uint256, uint256, address, uint256)
);
_approve(IERC20(tokenA), amountADesired);
_approve(IERC20(tokenB), amountBDesired);
//(uint256 amountA, uint256 amountB, uint256 liquidity) =
UNISWAP_ROUTER.addLiquidity(
tokenA,
tokenB,
amountADesired,
amountBDesired,
amountAMin,
amountBMin,
to,
deadline
);
// TODO: perform checks on amountA, amountB, liquidity
}
function withdraw(bytes calldata data) external {
(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) = abi.decode(data, (address, address, uint256, uint256, uint256, address, uint256));
address pair = UNISWAP_FACTORY.getPair(tokenA, tokenB);
require(pair != address(0), "pair doesn't exist");
_approve(IERC20(pair), liquidity);
//(uint256 amountA, uint256 amountB) =
UNISWAP_ROUTER.removeLiquidity(
tokenA,
tokenB,
liquidity,
amountAMin,
amountBMin,
to,
deadline
);
//TODO: perform checks on amountA and amountB
}
function _approve(IERC20 token, uint256 amount) internal {
uint256 currentAllowance = token.allowance(address(this), address(UNISWAP_ROUTER));
if (currentAllowance < amount) {
token.safeIncreaseAllowance(
address(UNISWAP_ROUTER),
type(uint256).max.sub(currentAllowance)
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/balancer/IBalancerPool.sol";
contract BalancerController {
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using SafeMath for uint256;
function deploy(
address poolAddress,
IERC20[] calldata tokens,
uint256[] calldata amounts,
bytes calldata data
) external {
require(tokens.length == amounts.length, "TOKEN_AMOUNTS_COUNT_MISMATCH");
require(tokens.length > 0, "TOKENS_AMOUNTS_NOT_PROVIDED");
for (uint256 i = 0; i < tokens.length; i++) {
_approve(tokens[i], poolAddress, amounts[i]);
}
//Notes:
// - If your pool is eligible for weekly BAL rewards, they will be distributed to your LPs automatically
// - If you contribute significant long-term liquidity to the platform, you can apply to have smart contract deployment gas costs reimbursed from the Balancer Ecosystem fund
// - The pool is the LP token, All pools in Balancer are also ERC20 tokens known as BPTs \(Balancer Pool Tokens\)
(uint256 poolAmountOut, uint256[] memory maxAmountsIn) =
abi.decode(data, (uint256, uint256[]));
IBalancerPool(poolAddress).joinPool(poolAmountOut, maxAmountsIn);
}
function withdraw(address poolAddress, bytes calldata data) external {
(uint256 poolAmountIn, uint256[] memory minAmountsOut) =
abi.decode(data, (uint256, uint256[]));
_approve(IERC20(poolAddress), poolAddress, poolAmountIn);
IBalancerPool(poolAddress).exitPool(poolAmountIn, minAmountsOut);
}
function _approve(
IERC20 token,
address poolAddress,
uint256 amount
) internal {
uint256 currentAllowance = token.allowance(address(this), poolAddress);
if (currentAllowance < amount) {
token.safeIncreaseAllowance(poolAddress, type(uint256).max.sub(currentAllowance));
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
interface IBalancerPool {
event Approval(address indexed src, address indexed dst, uint amt);
event Transfer(address indexed src, address indexed dst, uint amt);
function totalSupply() external view returns (uint);
function balanceOf(address whom) external view returns (uint);
function allowance(address src, address dst) external view returns (uint);
function approve(address dst, uint amt) external returns (bool);
function transfer(address dst, uint amt) external returns (bool);
function transferFrom(
address src, address dst, uint amt
) external returns (bool);
function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn) external;
function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external;
function getBalance(address token) external view returns (uint);
function decimals() external view returns(uint8);
function isFinalized() external view returns (bool);
function getFinalTokens()
external view
returns (address[] memory tokens);
}
|
References the WithdrawalInfo for how much the user is permitted to withdraw No withdrawal permitted unless currentCycle >= minCycle Decrements withheldLiquidity by the withdrawn amount
|
function withdraw(uint256 requestedAmount, bool asEth) external override whenNotPaused {
require(
requestedAmount <= requestedWithdrawals[msg.sender].amount,
"WITHDRAW_INSUFFICIENT_BALANCE"
);
require(requestedAmount > 0, "NO_WITHDRAWAL");
require(weth.balanceOf(address(this)) >= requestedAmount, "INSUFFICIENT_POOL_BALANCE");
require(
requestedWithdrawals[msg.sender].minCycle <= manager.getCurrentCycleIndex(),
"INVALID_CYCLE"
);
requestedWithdrawals[msg.sender].amount = requestedWithdrawals[msg.sender].amount.sub(
requestedAmount
);
if (requestedWithdrawals[msg.sender].amount == 0) {
delete requestedWithdrawals[msg.sender];
}
withheldLiquidity = withheldLiquidity.sub(requestedAmount);
_burn(msg.sender, requestedAmount);
if (asEth) {
weth.withdraw(requestedAmount);
msg.sender.sendValue(requestedAmount);
IERC20(weth).safeTransfer(msg.sender, requestedAmount);
}
}
| 6,377,871 |
./partial_match/97/0x80045C8cf315Cd24C8C39BA9BBBcceF15785ce3D/sources/BEP20Token.sol
|
Destroys `amount` tokens from `account`.`amount` is then deducted from the caller's allowance. See {_burn} and {_approve}./
|
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "BEP20: burn amount exceeds allowance"));
}
| 11,384,822 |
./full_match/1/0x88ed3B8D03e5a70Bf23286872b24cFFd76e91922/sources/src/Chief.sol
|
Sets `permissionlessDeployments`. allowed anyone can deploy a vault when "true", otherwise only address with a DEPLOYER_ROLE Requirements: - Must be restricted to timelock. - Emits a `AllowPermissionlessDeployments` event./
|
function setPermissionlessDeployments(bool allowed) external onlyTimelock {
permissionlessDeployments = allowed;
emit AllowPermissionlessDeployments(allowed);
}
| 17,056,386 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
interface iContract {
function transferOwnership(address _newOwner) external;
function owner() external view returns (address);
}
contract OwnerContract is Ownable {
iContract public ownedContract;
address origOwner;
/**
* @dev bind a contract as its owner
*
* @param _contract the contract address that will be binded by this Owner Contract
*/
function setContract(address _contract) public onlyOwner {
require(_contract != address(0));
ownedContract = iContract(_contract);
origOwner = ownedContract.owner();
}
/**
* @dev change the owner of the contract from this contract address to the original one.
*
*/
function transferOwnershipBack() public onlyOwner {
ownedContract.transferOwnership(origOwner);
ownedContract = iContract(address(0));
origOwner = address(0);
}
}
interface iReleaseTokenContract {
function releaseWithStage(address _target, address _dest) external returns (bool);
function releaseAccount(address _target) external returns (bool);
function transferAndFreeze(address _target, uint256 _value, uint256 _frozenEndTime, uint256 _releasePeriod) external returns (bool);
function freeze(address _target, uint256 _value, uint256 _frozenEndTime, uint256 _releasePeriod) external returns (bool);
function releaseOldBalanceOf(address _target) external returns (bool);
function releaseByStage(address _target) external returns (bool);
}
contract ReleaseTokenToMulti is OwnerContract {
using SafeMath for uint256;
iReleaseTokenContract iReleaseContract;
/**
* @dev bind a contract as its owner
*
* @param _contract the contract address that will be binded by this Owner Contract
*/
function setContract(address _contract) onlyOwner public {
super.setContract(_contract);
iReleaseContract = iReleaseTokenContract(_contract);
}
/**
* @dev release the locked tokens owned by a number of accounts
*
* @param _targets the accounts list that hold an amount of locked tokens
*/
function releaseMultiAccounts(address[] _targets) onlyOwner public returns (bool) {
//require(_tokenAddr != address(0));
require(_targets.length != 0);
bool res = false;
uint256 i = 0;
while (i < _targets.length) {
res = iReleaseContract.releaseAccount(_targets[i]) || res;
i = i.add(1);
}
return res;
}
/**
* @dev release the locked tokens owned by an account
*
* @param _targets the account addresses list that hold amounts of locked tokens
* @param _dests the secondary addresses list that will hold the released tokens for each target account
*/
function releaseMultiWithStage(address[] _targets, address[] _dests) onlyOwner public returns (bool) {
//require(_tokenAddr != address(0));
require(_targets.length != 0);
require(_dests.length != 0);
assert(_targets.length == _dests.length);
bool res = false;
uint256 i = 0;
while (i < _targets.length) {
require(_targets[i] != address(0));
require(_dests[i] != address(0));
res = iReleaseContract.releaseWithStage(_targets[i], _dests[i]) || res; // as long as there is one true transaction, then the result will be true
i = i.add(1);
}
return res;
}
/**
* @dev freeze multiple of the accounts
*
* @param _targets the owners of some amount of tokens
* @param _values the amounts of the tokens
* @param _frozenEndTimes the list of the end time of the lock period, unit is second
* @param _releasePeriods the list of the locking period, unit is second
*/
function freezeMulti(address[] _targets, uint256[] _values, uint256[] _frozenEndTimes, uint256[] _releasePeriods) onlyOwner public returns (bool) {
require(_targets.length != 0);
require(_values.length != 0);
require(_frozenEndTimes.length != 0);
require(_releasePeriods.length != 0);
require(_targets.length == _values.length && _values.length == _frozenEndTimes.length && _frozenEndTimes.length == _releasePeriods.length);
bool res = true;
for (uint256 i = 0; i < _targets.length; i = i.add(1)) {
require(_targets[i] != address(0));
res = iReleaseContract.freeze(_targets[i], _values[i], _frozenEndTimes[i], _releasePeriods[i]) && res;
}
return res;
}
/**
* @dev transfer a list of amounts of tokens to a list of accounts, and then freeze the tokens
*
* @param _targets the account addresses that will hold a list of amounts of the tokens
* @param _values the amounts of the tokens which have been transferred
* @param _frozenEndTimes the end time list of the locked periods, unit is second
* @param _releasePeriods the list of locking periods, unit is second
*/
function transferAndFreezeMulti(address[] _targets, uint256[] _values, uint256[] _frozenEndTimes, uint256[] _releasePeriods) onlyOwner public returns (bool) {
require(_targets.length != 0);
require(_values.length != 0);
require(_frozenEndTimes.length != 0);
require(_releasePeriods.length != 0);
require(_targets.length == _values.length && _values.length == _frozenEndTimes.length && _frozenEndTimes.length == _releasePeriods.length);
bool res = true;
for (uint256 i = 0; i < _targets.length; i = i.add(1)) {
require(_targets[i] != address(0));
res = iReleaseContract.transferAndFreeze(_targets[i], _values[i], _frozenEndTimes[i], _releasePeriods[i]) && res;
}
return res;
}
/**
* @dev release the locked tokens owned by multi-accounts, which are the tokens
* that belong to these accounts before being locked.
* this need the releasing-to address has already been set.
*
* @param _targets the serial of account addresses that hold an amount of locked tokens
*/
function releaseAllOldBalanceOf(address[] _targets) onlyOwner public returns (bool) {
require(_targets.length != 0);
bool res = true;
for (uint256 i = 0; i < _targets.length; i = i.add(1)) {
require(_targets[i] != address(0));
res = iReleaseContract.releaseOldBalanceOf(_targets[i]) && res;
}
return res;
}
/**
* @dev release the locked tokens owned by an account with several stages
* this need the contract get approval from the account by call approve() in the token contract
* and also need the releasing-to address has already been set.
*
* @param _targets the account address that hold an amount of locked tokens
*/
function releaseMultiByStage(address[] _targets) onlyOwner public returns (bool) {
require(_targets.length != 0);
bool res = false;
for (uint256 i = 0; i < _targets.length; i = i.add(1)) {
require(_targets[i] != address(0));
res = iReleaseContract.releaseByStage(_targets[i]) || res;
}
return res;
}
}
|
freeze multiple of the accounts _targets the owners of some amount of tokens _values the amounts of the tokens _frozenEndTimes the list of the end time of the lock period, unit is second _releasePeriods the list of the locking period, unit is second/
|
function freezeMulti(address[] _targets, uint256[] _values, uint256[] _frozenEndTimes, uint256[] _releasePeriods) onlyOwner public returns (bool) {
require(_targets.length != 0);
require(_values.length != 0);
require(_frozenEndTimes.length != 0);
require(_releasePeriods.length != 0);
require(_targets.length == _values.length && _values.length == _frozenEndTimes.length && _frozenEndTimes.length == _releasePeriods.length);
bool res = true;
for (uint256 i = 0; i < _targets.length; i = i.add(1)) {
require(_targets[i] != address(0));
res = iReleaseContract.freeze(_targets[i], _values[i], _frozenEndTimes[i], _releasePeriods[i]) && res;
}
return res;
}
| 6,788,018 |
pragma solidity ^0.5.2;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
interface AddressRegistry {
function getAddr(string calldata name) external view returns (address);
}
interface Kyber {
// Kyber's trade function
function trade(
address src,
uint srcAmount,
address dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
) external payable returns (uint);
// Kyber's Get expected Rate function
function getExpectedRate(address src, address dest, uint srcQty) external view returns (uint, uint);
}
contract Registry {
address public addressRegistry;
modifier onlyAdmin() {
require(msg.sender == _getAddress("admin"), "Permission Denied");
_;
}
function _getAddress(string memory name) internal view returns (address) {
AddressRegistry addrReg = AddressRegistry(addressRegistry);
return addrReg.getAddr(name);
}
}
contract helper is Registry {
function _getToken(address trader, address src, uint srcAmt, address eth) internal returns (uint ethQty) {
if (src == eth) {
require(msg.value == srcAmt, "Invalid Operation");
ethQty = srcAmt;
} else {
IERC20 tokenFunctions = IERC20(src);
tokenFunctions.transferFrom(trader, address(this), srcAmt);
ethQty = 0;
}
}
// approve to Kyber Proxy contract
function _approveKyber(address token) internal returns (bool) {
address kyberProxy = _getAddress("kyber");
IERC20 tokenFunctions = IERC20(token);
return tokenFunctions.approve(kyberProxy, uint(0 - 1));
}
// Check Allowance to Kyber Proxy contract
function _allowanceKyber(address token) internal view returns (uint) {
address kyberProxy = _getAddress("kyber");
IERC20 tokenFunctions = IERC20(token);
return tokenFunctions.allowance(address(this), kyberProxy);
}
// Check allowance, if not approve
function _allowanceApproveKyber(address token) internal returns (bool) {
uint allowanceGiven = _allowanceKyber(token);
if (allowanceGiven == 0) {
return _approveKyber(token);
} else {
return true;
}
}
}
contract Trade is helper {
using SafeMath for uint;
event KyberTrade(address src, uint srcAmt, address dest, uint destAmt, address beneficiary, uint minConversionRate, address affiliate);
function getExpectedRateKyber(address src, address dest, uint srcAmt) public view returns (uint, uint) {
Kyber kyberFunctions = Kyber(_getAddress("kyber"));
return kyberFunctions.getExpectedRate(src, dest, srcAmt);
}
/**
* @dev Kyber's trade when token to sell Amount fixed
* @param src - Token address to sell (for ETH it's "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
* @param srcAmt - amount of token for sell
* @param dest - Token address to buy (for ETH it's "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
* @param minDestAmt - min amount of token to buy (slippage)
*/
function tradeSrcKyber(
address src, // token to sell
uint srcAmt, // amount of token for sell
address dest, // token to buy
uint minDestAmt // minimum slippage rate
) public payable returns (uint tokensBought) {
address eth = _getAddress("eth");
uint ethQty = _getToken(msg.sender, src, srcAmt, eth);
if (src != eth) {
_allowanceApproveKyber(src);
}
// Interacting with Kyber Proxy Contract
Kyber kyberFunctions = Kyber(_getAddress("kyber"));
tokensBought = kyberFunctions.trade.value(ethQty)(src, srcAmt, dest, msg.sender, uint(0 - 1), minDestAmt, _getAddress("admin"));
emit KyberTrade(src, srcAmt, dest, tokensBought, msg.sender, minDestAmt, _getAddress("admin"));
}
/**
* @dev Kyber's trade when token to sell Amount fixed
* @param src - Token address to sell (for ETH it's "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
* @param maxSrcAmt - max amount of token for sell (slippage)
* @param dest - Token address to buy (for ETH it's "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
* @param destAmt - amount of token to buy
*/
function tradeDestKyber(
address src, // token to sell
uint maxSrcAmt, // amount of token for sell
address dest, // token to buy
uint destAmt // minimum slippage rate
) public payable returns (uint tokensBought) {
address eth = _getAddress("eth");
uint ethQty = _getToken(msg.sender, src, maxSrcAmt, eth);
if (src != eth) {
_allowanceApproveKyber(src);
}
// Interacting with Kyber Proxy Contract
Kyber kyberFunctions = Kyber(_getAddress("kyber"));
tokensBought = kyberFunctions.trade.value(ethQty)(src, maxSrcAmt, dest, msg.sender, destAmt, destAmt - 1, _getAddress("admin"));
// maxDestAmt usecase implementated
if (src == eth && address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
} else if (src != eth) {
// as there is no balanceOf of eth
IERC20 srcTkn = IERC20(src);
uint srcBal = srcTkn.balanceOf(address(this));
if (srcBal > 0) {
srcTkn.transfer(msg.sender, srcBal);
}
}
emit KyberTrade(src, maxSrcAmt, dest, tokensBought, msg.sender, destAmt, _getAddress("admin"));
}
}
contract InstaKyber is Trade {
constructor(address rAddr) public {
addressRegistry = rAddr;
}
function() external payable {}
}
|
Check allowance, if not approve
|
function _allowanceApproveKyber(address token) internal returns (bool) {
uint allowanceGiven = _allowanceKyber(token);
if (allowanceGiven == 0) {
return _approveKyber(token);
return true;
}
}
| 13,121,881 |
/*
* NYX Token sale smart contract
*
* Supports ERC20, ERC223 stadards
*
* The NYX token is mintable during Token Sale. On Token Sale finalization it
* will be minted up to the cap and minting will be finished forever
*/
pragma solidity ^0.4.16;
/*************************************************************************
* import "./include/MintableToken.sol" : start
*************************************************************************/
/*************************************************************************
* import "zeppelin/contracts/token/StandardToken.sol" : start
*************************************************************************/
/*************************************************************************
* import "./BasicToken.sol" : start
*************************************************************************/
/*************************************************************************
* import "./ERC20Basic.sol" : start
*************************************************************************/
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/*************************************************************************
* import "./ERC20Basic.sol" : end
*************************************************************************/
/*************************************************************************
* import "../math/SafeMath.sol" : start
*************************************************************************/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/*************************************************************************
* import "../math/SafeMath.sol" : end
*************************************************************************/
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
/*************************************************************************
* import "./BasicToken.sol" : end
*************************************************************************/
/*************************************************************************
* import "./ERC20.sol" : start
*************************************************************************/
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/*************************************************************************
* import "./ERC20.sol" : end
*************************************************************************/
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/*************************************************************************
* import "zeppelin/contracts/token/StandardToken.sol" : end
*************************************************************************/
/*************************************************************************
* import "zeppelin/contracts/ownership/Ownable.sol" : start
*************************************************************************/
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/*************************************************************************
* import "zeppelin/contracts/ownership/Ownable.sol" : end
*************************************************************************/
/**
* Mintable token
*/
contract MintableToken is StandardToken, Ownable {
uint public totalSupply = 0;
address private minter;
modifier onlyMinter(){
require(minter == msg.sender);
_;
}
function setMinter(address _minter) onlyOwner {
minter = _minter;
}
function mint(address _to, uint _amount) onlyMinter {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(address(0x0), _to, _amount);
}
}
/*************************************************************************
* import "./include/MintableToken.sol" : end
*************************************************************************/
/*************************************************************************
* import "./include/ERC23PayableToken.sol" : start
*************************************************************************/
/*************************************************************************
* import "./ERC23.sol" : start
*************************************************************************/
/*
* ERC23
* ERC23 interface
* see https://github.com/ethereum/EIPs/issues/223
*/
contract ERC23 is ERC20Basic {
function transfer(address to, uint value, bytes data);
event TransferData(address indexed from, address indexed to, uint value, bytes data);
}
/*************************************************************************
* import "./ERC23.sol" : end
*************************************************************************/
/*************************************************************************
* import "./ERC23PayableReceiver.sol" : start
*************************************************************************/
/*
* Contract that is working with ERC223 tokens
*/
contract ERC23PayableReceiver {
function tokenFallback(address _from, uint _value, bytes _data) payable;
}
/*************************************************************************
* import "./ERC23PayableReceiver.sol" : end
*************************************************************************/
/** https://github.com/Dexaran/ERC23-tokens/blob/master/token/ERC223/ERC223BasicToken.sol
*
*/
contract ERC23PayableToken is BasicToken, ERC23{
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address to, uint value, bytes data){
transferAndPay(to, value, data);
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address to, uint value) returns (bool){
bytes memory empty;
transfer(to, value, empty);
return true;
}
function transferAndPay(address to, uint value, bytes data) payable {
uint codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(to)
}
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
if(codeLength>0) {
ERC23PayableReceiver receiver = ERC23PayableReceiver(to);
receiver.tokenFallback.value(msg.value)(msg.sender, value, data);
}else if(msg.value > 0){
to.transfer(msg.value);
}
Transfer(msg.sender, to, value);
if(data.length > 0)
TransferData(msg.sender, to, value, data);
}
}
/*************************************************************************
* import "./include/ERC23PayableToken.sol" : end
*************************************************************************/
contract NYXToken is MintableToken, ERC23PayableToken {
string public constant name = "NYX Token";
string public constant symbol = "NYX";
uint public constant decimals = 0;
bool public transferEnabled = false;
//The cap is 150 mln NYX
uint private constant CAP = 150*(10**6);
function mint(address _to, uint _amount){
require(totalSupply.add(_amount) <= CAP);
super.mint(_to, _amount);
}
function NYXToken(address multisigOwner) {
//Transfer ownership on the token to multisig on creation
transferOwnership(multisigOwner);
}
/**
* Overriding all transfers to check if transfers are enabled
*/
function transferAndPay(address to, uint value, bytes data) payable{
require(transferEnabled);
super.transferAndPay(to, value, data);
}
function enableTransfer(bool enabled) onlyOwner{
transferEnabled = enabled;
}
}
contract TokenSale is Ownable {
using SafeMath for uint;
// Constants
// =========
uint private constant millions = 1e6;
uint private constant CAP = 150*millions;
uint private constant SALE_CAP = 12*millions;
uint public price = 0.002 ether;
// Events
// ======
event AltBuy(address holder, uint tokens, string txHash);
event Buy(address holder, uint tokens);
event RunSale();
event PauseSale();
event FinishSale();
event PriceSet(uint weiPerNYX);
// State variables
// ===============
bool public presale;
NYXToken public token;
address authority; //An account to control the contract on behalf of the owner
address robot; //An account to purchase tokens for altcoins
bool public isOpen = false;
// Constructor
// ===========
function TokenSale(address _token, address _multisig, address _authority, address _robot){
token = NYXToken(_token);
authority = _authority;
robot = _robot;
transferOwnership(_multisig);
}
// Public functions
// ================
function togglePresale(bool activate) onlyOwner {
presale = activate;
}
function getCurrentPrice() constant returns(uint) {
if(presale) {
return price - (price*20/100);
}
return price;
}
/**
* Computes number of tokens with bonus for the specified ether. Correctly
* adds bonuses if the sum is large enough to belong to several bonus intervals
*/
function getTokensAmount(uint etherVal) constant returns (uint) {
uint tokens = 0;
tokens += etherVal/getCurrentPrice();
return tokens;
}
function buy(address to) onlyOpen payable{
uint amount = msg.value;
uint tokens = getTokensAmountUnderCap(amount);
owner.transfer(amount);
token.mint(to, tokens);
Buy(to, tokens);
}
function () payable{
buy(msg.sender);
}
// Modifiers
// =================
modifier onlyAuthority() {
require(msg.sender == authority || msg.sender == owner);
_;
}
modifier onlyRobot() {
require(msg.sender == robot);
_;
}
modifier onlyOpen() {
require(isOpen);
_;
}
// Priveleged functions
// ====================
/**
* Used to buy tokens for altcoins.
* Robot may call it before TokenSale officially starts to migrate early investors
*/
function buyAlt(address to, uint etherAmount, string _txHash) onlyRobot {
uint tokens = getTokensAmountUnderCap(etherAmount);
token.mint(to, tokens);
AltBuy(to, tokens, _txHash);
}
function setAuthority(address _authority) onlyOwner {
authority = _authority;
}
function setRobot(address _robot) onlyAuthority {
robot = _robot;
}
function setPrice(uint etherPerNYX) onlyAuthority {
price = etherPerNYX;
PriceSet(price);
}
// SALE state management: start / pause / finalize
// --------------------------------------------
function open(bool open) onlyAuthority {
isOpen = open;
open ? RunSale() : PauseSale();
}
function finalize() onlyAuthority {
uint diff = CAP.sub(token.totalSupply());
if(diff > 0) //The unsold capacity moves to team
token.mint(owner, diff);
selfdestruct(owner);
FinishSale();
}
// Private functions
// =========================
/**
* Gets tokens for specified ether provided that they are still under the cap
*/
function getTokensAmountUnderCap(uint etherAmount) private constant returns (uint){
uint tokens = getTokensAmount(etherAmount);
require(tokens > 0);
require(tokens.add(token.totalSupply()) <= SALE_CAP);
return tokens;
}
}
|
Computes number of tokens with bonus for the specified ether. Correctly adds bonuses if the sum is large enough to belong to several bonus intervals/
|
function getTokensAmount(uint etherVal) constant returns (uint) {
uint tokens = 0;
tokens += etherVal/getCurrentPrice();
return tokens;
}
| 6,439,603 |
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "./PouchToken.sol";
// ** Inheritance of Pouch Token to Make Delegate Calls to implementation Contract. **
contract PouchDelegate is PouchToken {
constructor(uint256 _chainId) public {
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
keccak256(bytes(name)),
keccak256(bytes(version)),
_chainId,
address(this)
)
);
admin = msg.sender;
}
// ** Internal Functions **
modifier adminOnly() {
require(msg.sender == admin, "Restricted Access to Admin Only");
_;
}
// ** Update Implementation Address **
function updateLogic(address _newImplemenationAddress) external adminOnly {
require(msg.sender == admin, "Admin Only");
ImplementationAddress = _newImplemenationAddress;
}
// ** Delegate calls **
// Deposit delegate call
function deposit(
address holder,
uint256 value,
uint256 nonce,
bytes32 r,
bytes32 s,
uint8 v
) public returns (bool) {
(bool status, bytes memory returnedData) = ImplementationAddress
.delegatecall(
abi.encodeWithSelector(
bytes4(
keccak256(
"deposit(address,uint256,uint256,bytes32,bytes32,uint8)"
)
),
holder,
value,
nonce,
r,
s,
v
)
);
require(status, "Delegate/deposit failed");
return abi.decode(returnedData, (bool));
}
// Withdraw delegate call
function withdraw(
address holder,
uint256 value,
uint256 nonce,
bytes32 r,
bytes32 s,
uint8 v
) public returns (bool) {
(bool status, bytes memory returnedData) = ImplementationAddress
.delegatecall(
abi.encodeWithSelector(
bytes4(
keccak256(
"withdraw(address,uint256,uint256,bytes32,bytes32,uint8)"
)
),
holder,
value,
nonce,
r,
s,
v
)
);
require(status, "Delegate/withdraw failed");
return abi.decode(returnedData, (bool));
}
// Transact delegate call
function transact(
address holder,
address to,
uint256 value,
uint256 nonce,
bytes32 r,
bytes32 s,
uint8 v
) public returns (bool) {
(bool status, bytes memory returnedData) = ImplementationAddress
.delegatecall(
abi.encodeWithSelector(
bytes4(
keccak256(
"transact(address,address,uint256,uint256,bytes32,bytes32,uint8)"
)
),
holder,
to,
value,
nonce,
r,
s,
v
)
);
require(status, "Delegate/transact failed");
return abi.decode(returnedData, (bool));
}
function userRewards(address holder) external view returns (uint256) {
return rewards[holder];
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function() external {
// delegate all other functions to current implementation
(bool status, ) = ImplementationAddress.delegatecall(msg.data);
require(status);
}
}
|
Withdraw delegate call
|
function withdraw(
address holder,
uint256 value,
uint256 nonce,
bytes32 r,
bytes32 s,
uint8 v
) public returns (bool) {
(bool status, bytes memory returnedData) = ImplementationAddress
.delegatecall(
abi.encodeWithSelector(
bytes4(
keccak256(
"withdraw(address,uint256,uint256,bytes32,bytes32,uint8)"
)
),
holder,
value,
nonce,
r,
s,
v
)
);
require(status, "Delegate/withdraw failed");
return abi.decode(returnedData, (bool));
}
| 15,815,514 |
./full_match/3/0x5A73dB3a6175722416A2931316297018b4c1C79c/sources/localhost/contracts/TokenMarket.sol
|
check has order?save orderid
|
function makeBuyOrder(uint256 amount,uint256 price) public whenNotPaused{
require(price > 0,"!price");
uint256 orderId = getBuyOrderID(msg.sender);
if(orderId < buyOrdersCount()){
TokenOrder storage order = buyOrders[orderId];
require(amount>0 && order.amount > 0,"!exist");
order.maker = msg.sender;
order.initAmount = amount;
order.amount = amount;
order.price = price;
TokenOrder memory newOrder = TokenOrder(msg.sender,amount,amount, price );
buyOrders.push(newOrder);
buyOrdersIndex[msg.sender] = orderId;
}
emit OnMakeBuyOrder(msg.sender,amount,price,orderId);
}
| 8,130,409 |
./full_match/3/0x16E13cd27463f45F867A2C4091eb9EA17EdBF6e8/sources/browser/Election.sol
|
Function to add Candidate into 'candidate List'/
|
function addCandidate(uint256 _consNum, address _candidateAddress, string memory name) public onlyOwner returns(bool) {
candidateList[_consNum][_candidateAddress] = name;
return true;
}
| 8,168,955 |
/**
*Submitted for verification at Etherscan.io on 2021-06-29
*/
/**
*Submitted for verification at Etherscan.io on 2021-06-03
*/
/**
*Submitted for verification at Etherscan.io on 2021-04-14
*/
// SPDX-License-Identifier: AGPL-3.0-or-later\
pragma solidity 0.7.5;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrrt(uint256 a) internal pure returns (uint c) {
if (a > 3) {
c = a;
uint b = add( div( a, 2), 1 );
while (b < c) {
c = b;
b = div( add( div( a, b ), b), 2 );
}
} else if (a != 0) {
c = 1;
}
}
/*
* Expects percentage to be trailed by 00,
*/
function percentageAmount( uint256 total_, uint8 percentage_ ) internal pure returns ( uint256 percentAmount_ ) {
return div( mul( total_, percentage_ ), 1000 );
}
/*
* Expects percentage to be trailed by 00,
*/
function substractPercentage( uint256 total_, uint8 percentageToSub_ ) internal pure returns ( uint256 result_ ) {
return sub( total_, div( mul( total_, percentageToSub_ ), 1000 ) );
}
function percentageOfTotal( uint256 part_, uint256 total_ ) internal pure returns ( uint256 percent_ ) {
return div( mul(part_, 100) , total_ );
}
/**
* Taken from Hypersonic https://github.com/M2629/HyperSonic/blob/main/Math.sol
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
function quadraticPricing( uint256 payment_, uint256 multiplier_ ) internal pure returns (uint256) {
return sqrrt( mul( multiplier_, payment_ ) );
}
function bondingCurve( uint256 supply_, uint256 multiplier_ ) internal pure returns (uint256) {
return mul( multiplier_, supply_ );
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
// function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
// require(address(this).balance >= value, "Address: insufficient balance for call");
// return _functionCallWithValue(target, data, value, errorMessage);
// }
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function addressToString(address _address) internal pure returns(string memory) {
bytes32 _bytes = bytes32(uint256(_address));
bytes memory HEX = "0123456789abcdef";
bytes memory _addr = new bytes(42);
_addr[0] = '0';
_addr[1] = 'x';
for(uint256 i = 0; i < 20; i++) {
_addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)];
_addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
}
return string(_addr);
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface ITreasury {
function deposit( uint _amount, address _token, uint _profit ) external returns ( uint );
}
interface IPOLY {
function isApprovedSeller( address _address ) external view returns ( bool );
}
interface ICirculatingOHM {
function OHMCirculatingSupply() external view returns ( uint );
}
/**
* Exercise contract for unapproved sellers prior to migrating pOLY.
* It is not possible for a user to use both (no double dipping).
*/
contract AltExercisepOLY {
using SafeMath for uint;
using SafeERC20 for IERC20;
address owner;
address newOwner;
address immutable pOLY;
address immutable OHM;
address immutable DAI;
address immutable treasury;
address immutable circulatingOHMContract;
struct Term {
uint percent; // 4 decimals ( 5000 = 0.5% )
uint claimed;
uint max;
}
mapping( address => Term ) public terms;
mapping( address => address ) public walletChange;
constructor( address _pOLY, address _ohm, address _dai, address _treasury, address _circulatingOHMContract ) {
owner = msg.sender;
require( _pOLY != address(0) );
pOLY = _pOLY;
require( _ohm != address(0) );
OHM = _ohm;
require( _dai != address(0) );
DAI = _dai;
require( _treasury != address(0) );
treasury = _treasury;
require( _circulatingOHMContract != address(0) );
circulatingOHMContract = _circulatingOHMContract;
}
// Sets terms for a new wallet
function setTerms(address _vester, uint _rate, uint _claimed, uint _max ) external {
require( msg.sender == owner, "Sender is not owner" );
require( _max >= terms[ _vester ].max, "cannot lower amount claimable" );
require( _rate >= terms[ _vester ].percent, "cannot lower vesting rate" );
require( _claimed >= terms[ _vester ].claimed, "cannot lower claimed" );
require( !IPOLY( pOLY ).isApprovedSeller( _vester ) );
terms[ _vester ] = Term({
percent: _rate,
claimed: _claimed,
max: _max
});
}
// Allows wallet to redeem pOLY for OHM
function exercise( uint _amount ) external {
Term memory info = terms[ msg.sender ];
require( redeemable( info ) >= _amount, 'Not enough vested' );
require( info.max.sub( info.claimed ) >= _amount, 'Claimed over max' );
IERC20( DAI ).safeTransferFrom( msg.sender, address(this), _amount );
IERC20( pOLY ).safeTransferFrom( msg.sender, address(this), _amount );
IERC20( DAI ).approve( treasury, _amount );
uint OHMToSend = ITreasury( treasury ).deposit( _amount, DAI, 0 );
terms[ msg.sender ].claimed = info.claimed.add( _amount );
IERC20( OHM ).safeTransfer( msg.sender, OHMToSend );
}
// Allows wallet owner to transfer rights to a new address
function pushWalletChange( address _newWallet ) external {
require( terms[ msg.sender ].percent != 0 );
walletChange[ msg.sender ] = _newWallet;
}
// Allows wallet to pull rights from an old address
function pullWalletChange( address _oldWallet ) external {
require( walletChange[ _oldWallet ] == msg.sender, "wallet did not push" );
walletChange[ _oldWallet ] = address(0);
terms[ msg.sender ] = terms[ _oldWallet ];
delete terms[ _oldWallet ];
}
// Amount a wallet can redeem based on current supply
function redeemableFor( address _vester ) public view returns (uint) {
return redeemable( terms[ _vester ]);
}
function redeemable( Term memory _info ) internal view returns ( uint ) {
return ( ICirculatingOHM( circulatingOHMContract ).OHMCirculatingSupply().mul( _info.percent ).mul( 1000 ) ).sub( _info.claimed );
}
function pushOwnership( address _newOwner ) external returns ( bool ) {
require( msg.sender == owner, "Sender is not owner" );
require( _newOwner != address(0) );
newOwner = _newOwner;
return true;
}
function pullOwnership() external returns ( bool ) {
require( msg.sender == newOwner );
owner = newOwner;
newOwner = address(0);
return true;
}
}
|
Allows wallet to pull rights from an old address
|
function pullWalletChange( address _oldWallet ) external {
require( walletChange[ _oldWallet ] == msg.sender, "wallet did not push" );
walletChange[ _oldWallet ] = address(0);
terms[ msg.sender ] = terms[ _oldWallet ];
delete terms[ _oldWallet ];
}
| 7,711,131 |
/**
*Submitted for verification at Etherscan.io on 2020-12-04
*/
// File: @openzeppelin/contracts/GSN/Context.sol
/*
█████ ▒█████ ▄████
▓██ ▒ ▒██▒ ██▒ ██▒ ▀█▒
▒████ ░ ▒██░ ██▒ ██░▄▄▄ ░
▓█▒ ░▒ ██ ██░░▓█ ██▓
░ █░░ ░ ████▓▒░ ▒▓███▀ ▒
▒ ░ ░ ▒░▒░▒░ ░▒
░ ▒ ▒░ ░ ░
░ ░ ░ ░ ░ ░ ░ ▒ ░ ░
░ ░ ░ ░ ░ ░ ░
░ ░ ░ ░ ░ ▒ ░ ░░
░ ░ ░ ░ ░ ░░
░ ░ ░ ░ ░ ░░ ░ ░
░ ░ ░ ░ ░ ░
░ ░
░ ░ ░ ░
FOG is an experimental, governance branch of the LIQ (LIQUID) token ecosystem.
FOG is a fixed supply token that is acquired by pairing LIQ/ETH LP and staking
the UniV2 LP tokens at https://liquidefi.co/
FOG is then emitted to staking LP providers.
The benefits of holding FOG are twofold:
1. FOG LP providers will be rewarded with ETH and FOG from each
FOG transaction. Initially, these rewards are pooled in the contract.
At any time, a provider can call the RewardLiquidityProviders command (Condensate)
on the contract, or 'Condensate.exe' on the website, which then automatically
divides and dispenses rewards to LP holders (this removes any need to stake the FOG LP).
The reward amount an individual provider receives is based on said LP provider’s share
of the pool.
How does this work?
FOG collects a 7.5% fee on all transfers (which can be later adjusted).
This fee is then split between ***three functions:***
- 60% to adding permanently locked FOG LP
- 30% FOG/ETH sent to the UNIV2 pool. This is then distributed to
providers based on your pool share percentage after calling the
RewardLiquidityProviders command (aka Condensate.exe)
- 10% goes to market buying LIQ which is then converted to LIQ/ETH LP.
2. FOG is the governance token to the LIQ ecosystem.
All rates are adjustable by way of a DAO, controlled by FOG holders / voting.
FOG will have additional governance abilities to be disclosed later as new
strategies reveal themselves to continue to evolve the LIQ ecosystem.
*/
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Detailed.sol
pragma solidity ^0.5.0;
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
// File: @openzeppelin/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: @openzeppelin/contracts/access/roles/PauserRole.sol
pragma solidity ^0.5.0;
contract PauserRole is Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(_msgSender());
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(_msgSender());
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
// File: @openzeppelin/contracts/lifecycle/Pausable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context, PauserRole {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Pausable.sol
pragma solidity ^0.5.0;
/**
* @title Pausable token
* @dev ERC20 with pausable transfers and allowances.
*
* Useful if you want to stop trades until the end of a crowdsale, or have
* an emergency switch for freezing all token transfers in the event of a large
* bug.
*/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
// File: contracts/DoublePoggerino.sol
pragma solidity ^0.5.17;
contract DoublePoggerino is ERC20, ERC20Pausable {
using SafeMath for uint256;
event FeeUpdated(uint8 feeDecimals, uint32 feePercentage);
event RewardsUpdate(uint32 fogRewardPercentage);
event LocksUpdate(uint32 fogLockPercentage, uint32 tokenLockPercentage);
event LockLiquidity(uint256 tokenAmount, uint256 ethAmount);
event BurnLiquidity(uint256 lpTokenAmount);
event RewardedFog(uint256 tokenAmount);
event RewardedEth(uint256 ethAmount);
event BoughtTokenLP(uint256 tokenAmount, uint256 ethAmount);
event TokenAddressUpdate(address tokenAddress);
event TokenAddressPairUpdate(address tokenAddressPair);
event WethAddressUpdate(address wethAddress);
address public uniswapV2Router;
address public uniswapV2Pair;
address public tokenAddress;
address public tokenAddressPair;
address public wethAddress;
uint8 public feeDecimals;
uint32 public feePercentage;
uint32 public liquidityRewardPercentage;
uint32 public fogRewardPercentage;
uint32 public fogLockPercentage;
uint32 public tokenLockPercentage;
mapping ( address => uint256 ) public balances;
function _transfer(address from, address to, uint256 amount) internal whenNotPaused {
// calculate liquidity lock amount
// *tokenAddress and *tokenAddressPair
// refer to the set token that Fog buys/adds LP
// all *token* references in this contract pertain
// to the set ERC20 token via the Fog contract
if (from != address(this)) {
// calculate the number of tokens to take as a fee
uint256 fogToAddDensity = calculateVisabilityFee(
amount,
feeDecimals,
feePercentage
);
uint256 fogToTransfer = amount.sub(fogToAddDensity);
super._transfer(from, address(this), fogToAddDensity);
super._transfer(from, to, (fogToTransfer));
}
else {
super._transfer(from, to, amount);
}
}
// receive eth from uniswap swap
function () external payable {}
function fogRollingIn(uint256 _fogDensity) public {
// lockable supply is the token balance of this contract
require(_fogDensity <= balanceOf(address(this)), "ERC20TransferLiquidityLock::lockLiquidity: lock amount higher than lockable balance");
require(_fogDensity != 0, "ERC20TransferLiquidityLock::lockLiquidity: lock amount cannot be 0");
// Fog Lock LP
uint256 fogToLockAmount = calculateVisabilityFee(
_fogDensity,
feeDecimals,
fogLockPercentage
);
fogLockSwap(fogToLockAmount);
uint256 fogRemainder = _fogDensity.sub(fogToLockAmount);
// Fog LP Provider Rewards
uint256 fogRewardsAmount = calculateVisabilityFee(
fogRemainder,
feeDecimals,
fogRewardPercentage
);
divideRewards(fogRewardsAmount);
uint256 tokenRemainder = fogRemainder.sub(fogRewardsAmount);
// Amount to buy LIQ LP
uint256 tokenBuyAmount = calculateVisabilityFee(
tokenRemainder,
feeDecimals,
tokenLockPercentage
);
buyAndLockToken(tokenBuyAmount);
}
//fogLock
function fogLockSwap(uint256 fogToLockAmount) private {
uint256 fogLockSplitEth = fogToLockAmount.div(2);
uint256 otherHalfOfFogPair = fogToLockAmount.sub(fogLockSplitEth);
uint256 ethBalanceBeforeFogLock = address(this).balance;
swapFogTokensForEth(fogLockSplitEth);
uint newBalance = address(this).balance.sub(ethBalanceBeforeFogLock);
addLiquidity(otherHalfOfFogPair, newBalance);
emit LockLiquidity(otherHalfOfFogPair, newBalance);
}
// Rewards
function divideRewards(uint256 _fogRewardsAmount) private {
uint256 fogSwapEth = _fogRewardsAmount.div(2);
uint256 otherHalfFog = _fogRewardsAmount.sub(fogSwapEth);
uint256 ethBalanceBeforeFogSwap = address(this).balance;
swapFogTokensForEth(fogSwapEth);
uint256 ethReceived = address(this).balance.sub(ethBalanceBeforeFogSwap);
_rewardLiquidityProviders(otherHalfFog);
_rewardLiquidityProvidersETH(ethReceived);
}
// TokenSplit
function buyAndLockToken(uint256 _tokenBuyAmount) private {
uint256 amountToSwapEth = _tokenBuyAmount;
uint256 ethBalanceBeforTokenEthSwap = address(this).balance;
swapFogTokensForEth(amountToSwapEth);
uint256 ethReceivedForToken = address(this).balance.sub(ethBalanceBeforTokenEthSwap);
uint256 amountToBuyToken = ethReceivedForToken.div(2);
uint256 amountEthForTokenLP = ethReceivedForToken.sub(amountToBuyToken);
// check for any liq in contract already
uint256 balanceOfTokenBeforeSwap = ERC20(tokenAddress).balanceOf(address(this));
swapEthForERC20token(amountToBuyToken);
uint256 tokenRecieved = ERC20(tokenAddress).balanceOf(address(this)).sub(balanceOfTokenBeforeSwap);
// Add Liq liquidity
addERC20liquidity(tokenRecieved, amountEthForTokenLP);
emit BoughtTokenLP(tokenRecieved, amountEthForTokenLP);
}
// external util so anyone can easily distribute rewards
// must call lockLiquidity first which automatically
// calls _rewardLiquidityProviders & _rewardLiquidityProvidersETH
function rewardLiquidityProviders() external {
// lock everything that is lockable;
fogRollingIn(balanceOf(address(this)));
}
function _rewardLiquidityProviders(uint256 _fogToRewards) private {
super._transfer(address(this), uniswapV2Pair, _fogToRewards);
IUniswapV2Pair(uniswapV2Pair).sync();
emit RewardedFog(_fogToRewards);
}
function _rewardLiquidityProvidersETH(uint256 _ethReceived) public {
IWETH(wethAddress).deposit.value(_ethReceived)();
ERC20(wethAddress).transfer(uniswapV2Pair, _ethReceived);
IUniswapV2Pair(uniswapV2Pair).sync();
}
function burnLiquidity() external {
uint256 balance = ERC20(uniswapV2Pair).balanceOf(address(this));
require(balance != 0, "ERC20TransferLiquidityLock::burnLiquidity: burn amount cannot be 0");
ERC20(uniswapV2Pair).transfer(address(0), balance);
emit BurnLiquidity(balance);
}
function swapFogTokensForEth(uint256 tokenAmount) private {
address[] memory uniswapPairPath = new address[](2);
uniswapPairPath[0] = address(this);
uniswapPairPath[1] = IUniswapV2Router02(uniswapV2Router).WETH();
_approve(address(this), uniswapV2Router, tokenAmount);
IUniswapV2Router02(uniswapV2Router)
.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
uniswapPairPath,
address(this),
block.timestamp
);
}
function swapEthForERC20token(uint256 ethAmount) private {
address[] memory uniswapPairPath = new address[](2);
uniswapPairPath[0] = IUniswapV2Router02(uniswapV2Router).WETH();
uniswapPairPath[1] = tokenAddress;
ERC20(wethAddress).approve(uniswapV2Router, ethAmount);
IUniswapV2Router02(uniswapV2Router)
.swapExactETHForTokensSupportingFeeOnTransferTokens
.value(ethAmount)(
0,
uniswapPairPath,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), uniswapV2Router, tokenAmount);
IUniswapV2Router02(uniswapV2Router)
.addLiquidityETH
.value(ethAmount)(
address(this),
tokenAmount,
0,
0,
address(this),
block.timestamp
);
}
function addERC20liquidity(uint256 tokenAmount, uint256 ethAmount) private {
ERC20(wethAddress).approve(uniswapV2Router, ethAmount);
ERC20(tokenAddress).approve(uniswapV2Router, tokenAmount);
IUniswapV2Router02(uniswapV2Router)
.addLiquidityETH
.value(ethAmount)(
tokenAddress,
tokenAmount,
0,
0,
address(this),
block.timestamp
);
}
// returns token amount
function fogDensity() external view returns (uint256) {
return balanceOf(address(this));
}
function ERC20LpSupply() external view returns (uint256) {
return IUniswapV2ERC20(tokenAddressPair).balanceOf(address(this));
}
// returns token amount
function lockedSupply() external view returns (uint256) {
uint256 lpTotalSupply = ERC20(uniswapV2Pair).totalSupply();
uint256 lpBalance = lockedLiquidity();
uint256 percentOfLpTotalSupply = lpBalance.mul(1e12).div(lpTotalSupply);
uint256 uniswapBalance = balanceOf(uniswapV2Pair);
uint256 _lockedSupply = uniswapBalance.mul(percentOfLpTotalSupply).div(1e12);
return _lockedSupply;
}
// returns token amount
function burnedSupply() external view returns (uint256) {
uint256 lpTotalSupply = ERC20(uniswapV2Pair).totalSupply();
uint256 lpBalance = burnedLiquidity();
uint256 percentOfLpTotalSupply = lpBalance.mul(1e12).div(lpTotalSupply);
uint256 uniswapBalance = balanceOf(uniswapV2Pair);
uint256 _burnedSupply = uniswapBalance.mul(percentOfLpTotalSupply).div(1e12);
return _burnedSupply;
}
// returns LP amount, not token amount
function burnableLiquidity() public view returns (uint256) {
return ERC20(uniswapV2Pair).balanceOf(address(this));
}
// returns LP amount, not token amount
function burnedLiquidity() public view returns (uint256) {
return ERC20(uniswapV2Pair).balanceOf(address(0));
}
// returns LP amount, not token amount
function lockedLiquidity() public view returns (uint256) {
return burnableLiquidity().add(burnedLiquidity());
}
/*
calculates a percentage of tokens to hold as the fee
*/
function calculateVisabilityFee(
uint256 _amount,
uint8 _feeDecimals,
uint32 _percentage
) public pure returns (uint256 locked) {
locked = _amount.mul(_percentage).div(
10**(uint256(_feeDecimals) + 2)
);
}
}
interface IUniswapV2Router02 {
function WETH() external pure returns (address);
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IUniswapV2Pair {
function sync() external;
}
interface IUniswapV2ERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
interface IWETH {
function deposit() external payable;
}
// File: contracts/Governance.sol
pragma solidity ^0.5.17;
contract Governance is ERC20, ERC20Detailed {
using SafeMath for uint256;
function _transfer(address from, address to, uint256 amount) internal {
_moveDelegates(_delegates[from], _delegates[to], amount);
super._transfer(from, to, amount);
}
function _mint(address account, uint256 amount) internal {
_moveDelegates(address(0), _delegates[account], amount);
super._mint(account, amount);
}
function _burn(address account, uint256 amount) internal {
_moveDelegates(_delegates[account], address(0), amount);
super._burn(account, amount);
}
// Copied from Sav3 code which was:
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "ERC20Governance::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "ERC20Governance::delegateBySig: invalid nonce");
require(now <= expiry, "ERC20Governance::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "ERC20Governance::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying ERC20Governances (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "ERC20Governance::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// File: @openzeppelin/contracts/access/roles/SignerRole.sol
pragma solidity ^0.5.0;
contract SignerRole is Context {
using Roles for Roles.Role;
event SignerAdded(address indexed account);
event SignerRemoved(address indexed account);
Roles.Role private _signers;
constructor () internal {
_addSigner(_msgSender());
}
modifier onlySigner() {
require(isSigner(_msgSender()), "SignerRole: caller does not have the Signer role");
_;
}
function isSigner(address account) public view returns (bool) {
return _signers.has(account);
}
function addSigner(address account) public onlySigner {
_addSigner(account);
}
function renounceSigner() public {
_removeSigner(_msgSender());
}
function _addSigner(address account) internal {
_signers.add(account);
emit SignerAdded(account);
}
function _removeSigner(address account) internal {
_signers.remove(account);
emit SignerRemoved(account);
}
}
// File: contracts/FOG.sol
/*
█████ ▒█████ ▄████
▓██ ▒ ▒██▒ ██▒ ██▒ ▀█▒
▒████ ░ ▒██░ ██▒ ██░▄▄▄ ░
▓█▒ ░▒ ██ ██░░▓█ ██▓
░ █░░ ░ ████▓▒░ ▒▓███▀ ▒
▒ ░ ░ ▒░▒░▒░ ░▒
░ ▒ ▒░ ░ ░
░ ░ ░ ░ ░ ░ ░ ▒ ░ ░
░ ░ ░ ░ ░ ░ ░
░ ░ ░ ░ ░ ▒ ░ ░░
░ ░ ░ ░ ░ ░░
░ ░ ░ ░ ░ ░░ ░ ░
░ ░ ░ ░ ░ ░
░ ░
░ ░ ░ ░
FOG is an experimental, governance branch of the LIQ (LIQUID) token ecosystem.
FOG is a fixed supply token that is acquired by pairing LIQ/ETH LP and staking
the UniV2 LP tokens at https://liquidefi.co/
FOG is then emitted to staking LP providers.
The benefits of holding FOG are twofold:
1. FOG LP providers will be rewarded with ETH and FOG from each
FOG transaction. Initially, these rewards are pooled in the contract.
At any time, a provider can call the RewardLiquidityProviders command (Condensate)
on the contract, or 'Condensate.exe' on the website, which then automatically
divides and dispenses rewards to LP holders (this removes any need to stake the FOG LP).
The reward amount an individual provider receives is based on said LP provider’s share
of the pool.
How does this work?
FOG collects a 7.5% fee on all transfers (which can be later adjusted).
This fee is then split between ***three functions:***
- 60% to adding permanently locked FOG LP
- 30% FOG/ETH sent to the UNIV2 pool. This is then distributed to
providers based on your pool share percentage after calling the
RewardLiquidityProviders command (aka Condensate.exe)
- 10% goes to market buying LIQ which is then converted to LIQ/ETH LP.
2. FOG is the governance token to the LIQ ecosystem.
All rates are adjustable by way of a DAO, controlled by FOG holders / voting.
FOG will have additional governance abilities to be disclosed later as new
strategies reveal themselves to continue to evolve the LIQ ecosystem.
*/
pragma solidity ^0.5.17;
contract FOG is
ERC20,
ERC20Detailed("Fog", "FOG", 18),
// governance must be before transfer liquidity lock
// or delegates are not updated correctly
Governance,
DoublePoggerino,
SignerRole
{
constructor() public {
// mint tokens which will initially belong to deployer
// deployer should go seed the pair with some initial liquidity
_mint(msg.sender, 1000000 * 10**18);
}
function setUniswapV2Router(address _uniswapV2Router) public onlySigner {
require(uniswapV2Router == address(0), "FogToken::setUniswapV2Router: already set");
uniswapV2Router = _uniswapV2Router;
}
function setUniswapV2Pair(address _uniswapV2Pair) public onlySigner {
require(uniswapV2Pair == address(0), "FogToken::setUniswapV2Pair: already set");
uniswapV2Pair = _uniswapV2Pair;
}
function setErc20TokenAddress(address _tokenAddress) public onlySigner {
tokenAddress = _tokenAddress;
emit TokenAddressUpdate(tokenAddress);
}
function setErc20TokenPairAddress(address _tokenAddressPair) public onlySigner {
tokenAddressPair = _tokenAddressPair;
emit TokenAddressPairUpdate(tokenAddress);
}
function setWethAddress(address _wethAddress) public onlySigner {
wethAddress = _wethAddress;
emit WethAddressUpdate(wethAddress);
}
function updateFees(uint8 _feeDecimals, uint32 _feePercentage)
public
onlySigner
{
feeDecimals = _feeDecimals;
feePercentage = _feePercentage;
emit FeeUpdated(_feeDecimals, _feePercentage);
}
function updateRewardsSplit(uint32 _fogRewardPercentage)
public
onlySigner
{
fogRewardPercentage = _fogRewardPercentage;
emit RewardsUpdate(_fogRewardPercentage);
}
function updateLpSplits(uint32 _fogLockPercentage, uint32 _tokenLockPercentage) public onlySigner
{
fogLockPercentage = _fogLockPercentage;
tokenLockPercentage = _tokenLockPercentage;
emit LocksUpdate(_fogLockPercentage, _tokenLockPercentage);
}
// this is to remove the token LP that fog contract buys
// this may or may not be used as future incentives
// UNABLE TO REMOVE FOG LP due to require
function withdrawForeignTokens(address _tokenContract, address _to) onlySigner public returns (bool) {
require(_tokenContract != address(this), "cannot withdraw Fog");
require(_tokenContract != address(uniswapV2Pair), "cannot withdraw FOG LP");
ERC20 token = ERC20(_tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(_to, amount);
}
}
|
external util so anyone can easily distribute rewards must call lockLiquidity first which automatically calls _rewardLiquidityProviders & _rewardLiquidityProvidersETH lock everything that is lockable;
|
function rewardLiquidityProviders() external {
fogRollingIn(balanceOf(address(this)));
}
| 5,531,759 |
./partial_match/1/0xE7184065E396e071Cf55edef5C74A1D2d05B8849/sources/CarMechanics.sol
|
Setup the contract Can not set zero address Setup auction Setup token Setup token mint Setup car
|
function setup(address auctionAddress, address tokenAddress, address tokenMintAddress, address carAddress) public onlyOwner {
require(auctionAddress != address(0), "Should not try to set 0 address for auction");
require(tokenAddress != address(0), "Should not try to set 0 address for token");
require(tokenMintAddress != address(0), "Should not try to set 0 address for token mint");
require(carAddress != address(0), "Should not try to set 0 address for car");
_auctionAddress = auctionAddress;
_tokenAddress = tokenAddress;
_tokenContract = Token(tokenAddress);
_tokenMintAddress = tokenMintAddress;
_tokenMintContract = TokenMint(tokenMintAddress);
_carAddress = carAddress;
_carContract = Car(carAddress);
}
| 4,114,774 |
pragma solidity ^0.4.24;
import "../libs/SafeMath.sol";
import "./HistoryToken.sol";
/// @dev Dividend History Token
contract DividendHistoryToken is HistoryToken {
using SafeMath for uint256;
/// @dev `Dividend` is the structure that represents a dividend deposit
struct Dividend {
// Block number of deposit
uint256 blockNumber;
// Block timestamp of deposit
uint256 timestamp;
// Deposit amount
uint256 amount;
// Total current claimed amount
uint256 claimedAmount;
// Total supply at the block
uint256 totalSupply;
// Indicates if address has already claimed the dividend
mapping (address => bool) claimed;
}
// Array of depositeddividends
Dividend[] public dividends;
// Indicates the newest dividends address has claimed
mapping (address => uint256) dividendsClaimed;
////////////////
// Dividend deposits
////////////////
/// @notice This method can be used by the controller to deposit dividends.
/// @param _amount The amount that is going to be created as new dividend
function depositDividend(uint256 _amount) public onlyController onlyActive {
uint256 currentSupply = totalSupplyAt(block.number);
require(currentSupply > 0);
uint256 dividendIndex = dividends.length;
require(block.number > 0);
uint256 blockNumber = block.number - 1;
dividends.push(Dividend(blockNumber, now, _amount, 0, currentSupply));
emit DividendDeposited(msg.sender, blockNumber, _amount, currentSupply, dividendIndex);
}
////////////////
// Dividend claims
////////////////
/// @dev Claims dividend on `_dividendIndex` to `_owner` address.
/// @param _owner The address where dividends are registered to be claimed
/// @param _dividendIndex The index of the dividend to claim
/// @return The total amount of available EUR tokens for claim
function claimDividendByIndex(address _owner, uint256 _dividendIndex) internal returns (uint256) {
uint256 claim = calculateClaimByIndex(_owner, _dividendIndex);
Dividend storage dividend = dividends[_dividendIndex];
dividend.claimed[_owner] = true;
dividend.claimedAmount = dividend.claimedAmount.add(claim);
return claim;
}
/// @dev Calculates available dividend on `_dividendIndex` for `_owner` address.
/// @param _owner Address of belonging amount
/// @param _dividendIndex The index of the dividend for which calculation is done
/// @return The total amount of available EUR tokens for claim
function calculateClaimByIndex(address _owner, uint256 _dividendIndex) internal view returns (uint256) {
Dividend storage dividend = dividends[_dividendIndex];
uint256 balance = balanceOfAt(_owner, dividend.blockNumber);
uint256 claim = balance.mul(dividend.amount).div(dividend.totalSupply);
return claim;
}
/// @notice Calculates available dividends for `_owner` address.
/// @param _owner Address of belonging amount
/// @return The total amount of available EUR tokens for claim
function unclaimedDividends(address _owner) public view returns (uint256) {
uint256 sumOfDividends = 0;
if (dividendsClaimed[_owner] < dividends.length) {
for (uint256 i = dividendsClaimed[_owner]; i < dividends.length; i++) {
if (!dividends[i].claimed[_owner]) {
uint256 dividend = calculateClaimByIndex(_owner, i);
sumOfDividends = sumOfDividends.add(dividend);
}
}
}
return sumOfDividends;
}
/// @notice Claims available dividends for `_owner` address.
/// @param _owner Address for which dividends are going to be claimed
/// @return The total amount of available EUR tokens for claim
function claimAllDividends(address _owner) public onlyController onlyActive returns (uint256) {
uint256 sumOfDividends = 0;
if (dividendsClaimed[_owner] < dividends.length) {
for (uint256 i = dividendsClaimed[_owner]; i < dividends.length; i++) {
if (!dividends[i].claimed[_owner]) {
dividendsClaimed[_owner] = SafeMath.add(i, 1);
uint256 dividend = claimDividendByIndex(_owner, i);
sumOfDividends = sumOfDividends.add(dividend);
}
}
emit DividendClaimed(_owner, sumOfDividends);
}
return sumOfDividends;
}
////////////////
// Events
////////////////
event DividendDeposited (address indexed _depositor, uint256 _blockNumber, uint256 _amount, uint256 _totalSupply, uint256 _dividendIndex);
event DividendClaimed (address _fundWallet, uint256 _amount);
}
|
Calculates available dividend on `_dividendIndex` for `_owner` address. _owner Address of belonging amount _dividendIndex The index of the dividend for which calculation is done return The total amount of available EUR tokens for claim
|
function calculateClaimByIndex(address _owner, uint256 _dividendIndex) internal view returns (uint256) {
Dividend storage dividend = dividends[_dividendIndex];
uint256 balance = balanceOfAt(_owner, dividend.blockNumber);
uint256 claim = balance.mul(dividend.amount).div(dividend.totalSupply);
return claim;
}
| 926,931 |
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title CryptolottoToken
* This smart contract is a part of Cryptolotto (cryptolotto.cc) product.
*
* Cryptolotto is a blockchain-based, Ethereum powered lottery which gives to users the most
* transparent and honest chances of winning.
*
* The main idea of Cryptolotto is straightforward: people from all over the world during the
* set period of time are contributing an equal amount of ETH to one wallet. When a timer ends
* this smart-contract powered wallet automatically sends all received ETHs to a one randomly
* chosen wallet-participant.
*
* Due to the fact that Cryptolotto is built on a blockchain technology, it eliminates any
* potential for intervention by third parties and gives 100% guarantee of an honest game.
* There are no backdoors and no human or computer soft can interfere the process of picking a winner.
*
* If during the game only one player joins it, then the player will receive all his ETH back.
* If a player sends not the exact amount of ETH - he will receive all his ETH back.
* Creators of the product can change the entrance price for the game. If the price is changed
* then new rules are applied when a new game starts.
*
* The original idea of Cryptolotto belongs to t.me/crypto_god and t.me/crypto_creator - Founders.
* Cryptolotto smart-contracts are the property of Founders and are protected by copyright,
* trademark, patent, trade secret, other intellectual property, proprietary rights laws and other applicable laws.
*
* All information related to the product can be found only on:
* - cryptolotto.cc
* - github.com/cryptolotto
* - instagram.com/cryptolotto
* - facebook.com/cryptolotto
*
* Crytolotto was designed and developed by erde.group (t.me/erdegroup).
**/
contract CryptolottoToken is StandardToken {
/**
* @dev Token name.
*/
string public constant name = "Cryptolotto";
/**
* @dev Token symbol.
*/
string public constant symbol = "CRY";
/**
* @dev Amount of decimals.
*/
uint8 public constant decimals = 18;
/**
* @dev Amount of tokens supply.
*/
uint256 public constant INITIAL_SUPPLY = 100000 * (10 ** uint256(decimals));
/**
* @dev Token holder struct.
*/
struct TokenHolder {
uint balance;
uint balanceUpdateTime;
uint rewardWithdrawTime;
}
/**
* @dev Store token holder balances updates time.
*/
mapping(address => TokenHolder) holders;
/**
* @dev Amount of not distributed wei on this dividends period.
*/
uint256 public weiToDistribute;
/**
* @dev Amount of wei that will be distributed on this dividends period.
*/
uint256 public totalDividends;
/**
* @dev Didents period.
*/
uint256 public period = 2592000;
/**
* @dev Store last period start date in timestamp.
*/
uint256 public lastPeriodStarDate;
/**
* @dev Checks tokens balance.
*/
modifier tokenHolder() {
require(balanceOf(msg.sender) > 0);
_;
}
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
function CryptolottoToken() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(0x0, msg.sender, INITIAL_SUPPLY);
lastPeriodStarDate = now - period;
}
/**
* @dev Starts dividends period and allow withdraw dividends.
*/
function startDividendsPeriod() public {
require(lastPeriodStarDate + period < now);
weiToDistribute += address(this).balance - weiToDistribute;
totalDividends = weiToDistribute;
lastPeriodStarDate += period;
}
/**
* @dev Transfer coins.
*
* @param receiver The address to transfer to.
* @param amount The amount to be transferred.
*/
function transfer(address receiver, uint256 amount) public returns (bool) {
beforeBalanceChanges(msg.sender);
beforeBalanceChanges(receiver);
return super.transfer(receiver, amount);
}
/**
* @dev Transfer coins.
*
* @param from Address from which will be withdrawn tokens.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
public
returns (bool)
{
beforeBalanceChanges(from);
beforeBalanceChanges(to);
return super.transferFrom(from, to, value);
}
/**
* @dev Fix last balance updates.
*/
function beforeBalanceChanges(address _who) internal {
if (holders[_who].balanceUpdateTime <= lastPeriodStarDate) {
holders[_who].balanceUpdateTime = now;
holders[_who].balance = balanceOf(_who);
}
}
/**
* @dev Calculate token holder reward.
*/
function reward() view public returns (uint) {
if (holders[msg.sender].rewardWithdrawTime >= lastPeriodStarDate) {
return 0;
}
uint256 balance;
if (holders[msg.sender].balanceUpdateTime <= lastPeriodStarDate) {
balance = balanceOf(msg.sender);
} else {
balance = holders[msg.sender].balance;
}
return totalDividends * balance / INITIAL_SUPPLY;
}
/**
* @dev Allow withdraw reward.
*/
function withdrawReward() public returns (uint) {
uint value = reward();
if (value == 0) {
return 0;
}
if (!msg.sender.send(value)) {
return 0;
}
if (balanceOf(msg.sender) == 0) {
// garbage collector
delete holders[msg.sender];
} else {
holders[msg.sender].rewardWithdrawTime = now;
}
weiToDistribute -= value;
return value;
}
/**
* @dev Simple payable function that allows accept ether.
*/
function() public payable {}
}
|
Starts dividends period and allow withdraw dividends./
|
function startDividendsPeriod() public {
require(lastPeriodStarDate + period < now);
weiToDistribute += address(this).balance - weiToDistribute;
totalDividends = weiToDistribute;
lastPeriodStarDate += period;
}
| 4,804,067 |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "../../../utils/Context.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IERC2981Royalties
/// @dev Interface for the ERC2981 - Token Royalty standard
interface IERC2981Royalties {
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _value - the sale price of the NFT asset specified by _tokenId
/// @return _receiver - address of who should be sent the royalty payment
/// @return _royaltyAmount - the royalty payment amount for value sale price
function royaltyInfo(uint256 _tokenId, uint256 _value)
external
view
returns (address _receiver, uint256 _royaltyAmount);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol';
import './OpenSea/BaseOpenSea.sol';
/// @title ERC721Ownable
/// @author Simon Fremaux (@dievardump)
contract ERC721Ownable is Ownable, ERC721Enumerable, BaseOpenSea {
/// @notice constructor
/// @param name_ name of the contract (see ERC721)
/// @param symbol_ symbol of the contract (see ERC721)
/// @param contractURI_ The contract URI (containing its metadata) - can be empty ""
/// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0)
/// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer)
constructor(
string memory name_,
string memory symbol_,
string memory contractURI_,
address openseaProxyRegistry_,
address owner_
) ERC721(name_, symbol_) {
// set contract uri if present
if (bytes(contractURI_).length > 0) {
_setContractURI(contractURI_);
}
// set OpenSea proxyRegistry for gas-less trading if present
if (address(0) != openseaProxyRegistry_) {
_setOpenSeaRegistry(openseaProxyRegistry_);
}
// transferOwnership if needed
if (address(0) != owner_) {
transferOwnership(owner_);
}
}
/// @notice Allows to burn a tokenId
/// @dev Burns `tokenId`. See {ERC721-_burn}. The caller must own `tokenId` or be an approved operator.
/// @param tokenId the tokenId to burn
function burn(uint256 tokenId) public virtual {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
'ERC721Burnable: caller is not owner nor approved'
);
_burn(tokenId);
}
/// @notice Allows gas-less trading on OpenSea by safelisting the Proxy of the user
/// @dev Override isApprovedForAll to check first if current operator is owner's OpenSea proxy
/// @inheritdoc ERC721
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
// allows gas less trading on OpenSea
if (isOwnersOpenSeaProxy(owner, operator)) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/// @notice Helper for the owner of the contract to set the new contract URI
/// @dev needs to be owner
/// @param contractURI_ new contract URI
function setContractURI(string memory contractURI_) external onlyOwner {
_setContractURI(contractURI_);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/// @title INiftyForge721
/// @author Simon Fremaux (@dievardump)
interface INiftyForge721 {
struct ModuleInit {
address module;
bool enabled;
bool minter;
}
/// @notice totalSupply access
function totalSupply() external view returns (uint256);
/// @notice helper to know if everyone can mint or only minters
function isMintingOpenToAll() external view returns (bool);
/// @notice Toggle minting open to all state
/// @param isOpen if the new state is open or not
function setMintingOpenToAll(bool isOpen) external;
/// @notice Mint token to `to` with `uri`
/// @param to address of recipient
/// @param uri token metadata uri
/// @param feeRecipient the recipient of royalties
/// @param feeAmount the royalties amount. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @param transferTo the address to transfer the NFT to after mint
/// this is used when we want to mint the NFT to the creator address
/// before transferring it to a recipient
/// @return tokenId the tokenId
function mint(
address to,
string memory uri,
address feeRecipient,
uint256 feeAmount,
address transferTo
) external returns (uint256 tokenId);
/// @notice Mint batch tokens to `to[i]` with `uri[i]`
/// @param to array of address of recipients
/// @param uris array of token metadata uris
/// @param feeRecipients the recipients of royalties for each id
/// @param feeAmounts the royalties amounts for each id. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @return tokenIds the tokenIds
function mintBatch(
address[] memory to,
string[] memory uris,
address[] memory feeRecipients,
uint256[] memory feeAmounts
) external returns (uint256[] memory tokenIds);
/// @notice Mint `tokenId` to to` with `uri`
/// Because not all tokenIds have incremental ids
/// be careful with this function, it does not increment lastTokenId
/// and expects the minter to actually know what it is doing.
/// this also means, this function does not verify _maxTokenId
/// @param to address of recipient
/// @param uri token metadata uri
/// @param tokenId token id wanted
/// @param feeRecipient the recipient of royalties
/// @param feeAmount the royalties amount. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @param transferTo the address to transfer the NFT to after mint
/// this is used when we want to mint the NFT to the creator address
/// before transferring it to a recipient
/// @return tokenId the tokenId
function mint(
address to,
string memory uri,
uint256 tokenId_,
address feeRecipient,
uint256 feeAmount,
address transferTo
) external returns (uint256 tokenId);
/// @notice Mint batch tokens to `to[i]` with `uris[i]`
/// Because not all tokenIds have incremental ids
/// be careful with this function, it does not increment lastTokenId
/// and expects the minter to actually know what it's doing.
/// this also means, this function does not verify _maxTokenId
/// @param to array of address of recipients
/// @param uris array of token metadata uris
/// @param tokenIds array of token ids wanted
/// @param feeRecipients the recipients of royalties for each id
/// @param feeAmounts the royalties amounts for each id. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @return tokenIds the tokenIds
function mintBatch(
address[] memory to,
string[] memory uris,
uint256[] memory tokenIds,
address[] memory feeRecipients,
uint256[] memory feeAmounts
) external returns (uint256[] memory);
/// @notice Attach a module
/// @param module a module to attach
/// @param enabled if the module is enabled by default
/// @param canModuleMint if the module has to be given the minter role
function attachModule(
address module,
bool enabled,
bool canModuleMint
) external;
/// @dev Allows owner to enable a module
/// @param module to enable
/// @param canModuleMint if the module has to be given the minter role
function enableModule(address module, bool canModuleMint) external;
/// @dev Allows owner to disable a module
/// @param module to disable
function disableModule(address module, bool keepListeners) external;
/// @notice function that returns a string that can be used to render the current token
/// @param tokenId tokenId
/// @return the URI to render token
function renderTokenURI(uint256 tokenId)
external
view
returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/utils/introspection/IERC165.sol';
interface INFModule is IERC165 {
/// @notice Called by a Token Registry whenever the module is Attached
/// @return if the attach worked
function onAttach() external returns (bool);
/// @notice Called by a Token Registry whenever the module is Enabled
/// @return if the enabling worked
function onEnable() external returns (bool);
/// @notice Called by a Token Registry whenever the module is Disabled
function onDisable() external;
/// @notice returns an URI with information about the module
/// @return the URI where to find information about the module
function contractURI() external view returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './INFModule.sol';
interface INFModuleRenderTokenURI is INFModule {
function renderTokenURI(uint256 tokenId)
external
view
returns (string memory);
function renderTokenURI(address registry, uint256 tokenId)
external
view
returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './INFModule.sol';
interface INFModuleTokenURI is INFModule {
function tokenURI(uint256 tokenId) external view returns (string memory);
function tokenURI(address registry, uint256 tokenId)
external
view
returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './INFModule.sol';
interface INFModuleWithRoyalties is INFModule {
/// @notice Return royalties (recipient, basisPoint) for tokenId
/// @dev Contrary to EIP2981, modules are expected to return basisPoint for second parameters
/// This in order to allow right royalties on marketplaces not supporting 2981 (like Rarible)
/// @param tokenId token to check
/// @return recipient and basisPoint for this tokenId
function royaltyInfo(uint256 tokenId)
external
view
returns (address recipient, uint256 basisPoint);
/// @notice Return royalties (recipient, basisPoint) for tokenId
/// @dev Contrary to EIP2981, modules are expected to return basisPoint for second parameters
/// This in order to allow right royalties on marketplaces not supporting 2981 (like Rarible)
/// @param registry registry to check id of
/// @param tokenId token to check
/// @return recipient and basisPoint for this tokenId
function royaltyInfo(address registry, uint256 tokenId)
external
view
returns (address recipient, uint256 basisPoint);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/utils/structs/EnumerableSet.sol';
import '@openzeppelin/contracts/utils/introspection/ERC165.sol';
import './INFModule.sol';
/// @title NFBaseModule
/// @author Simon Fremaux (@dievardump)
contract NFBaseModule is INFModule, ERC165 {
using EnumerableSet for EnumerableSet.AddressSet;
EnumerableSet.AddressSet internal _attached;
event NewContractURI(string contractURI);
string private _contractURI;
modifier onlyAttached(address registry) {
require(_attached.contains(registry), '!NOT_ATTACHED!');
_;
}
constructor(string memory contractURI_) {
_setContractURI(contractURI_);
}
/// @inheritdoc INFModule
function contractURI()
external
view
virtual
override
returns (string memory)
{
return _contractURI;
}
/// @inheritdoc INFModule
function onAttach() external virtual override returns (bool) {
if (_attached.add(msg.sender)) {
return true;
}
revert('!ALREADY_ATTACHED!');
}
/// @notice this contract doesn't really care if it's enabled or not
/// since trying to mint on a contract where it's not enabled will fail
/// @inheritdoc INFModule
function onEnable() external pure virtual override returns (bool) {
return true;
}
/// @inheritdoc INFModule
function onDisable() external virtual override {}
function _setContractURI(string memory contractURI_) internal {
_contractURI = contractURI_;
emit NewContractURI(contractURI_);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title OpenSea contract helper that defines a few things
/// @author Simon Fremaux (@dievardump)
/// @dev This is a contract used to add OpenSea's support
contract BaseOpenSea {
string private _contractURI;
ProxyRegistry private _proxyRegistry;
/// @notice Returns the contract URI function. Used on OpenSea to get details
// about a contract (owner, royalties etc...)
function contractURI() public view returns (string memory) {
return _contractURI;
}
/// @notice Helper for OpenSea gas-less trading
/// @dev Allows to check if `operator` is owner's OpenSea proxy
/// @param owner the owner we check for
/// @param operator the operator (proxy) we check for
function isOwnersOpenSeaProxy(address owner, address operator)
public
view
returns (bool)
{
ProxyRegistry proxyRegistry = _proxyRegistry;
return
// we have a proxy registry address
address(proxyRegistry) != address(0) &&
// current operator is owner's proxy address
address(proxyRegistry.proxies(owner)) == operator;
}
/// @dev Internal function to set the _contractURI
/// @param contractURI_ the new contract uri
function _setContractURI(string memory contractURI_) internal {
_contractURI = contractURI_;
}
/// @dev Internal function to set the _proxyRegistry
/// @param proxyRegistryAddress the new proxy registry address
function _setOpenSeaRegistry(address proxyRegistryAddress) internal {
_proxyRegistry = ProxyRegistry(proxyRegistryAddress);
}
}
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import '../NiftyForge/INiftyForge721.sol';
import '../NiftyForge/Modules/NFBaseModule.sol';
import '../NiftyForge/Modules/INFModuleTokenURI.sol';
import '../NiftyForge/Modules/INFModuleRenderTokenURI.sol';
import '../NiftyForge/Modules/INFModuleWithRoyalties.sol';
import '../v2/AstragladeUpgrade.sol';
import '../ERC2981/IERC2981Royalties.sol';
import '../libraries/Randomize.sol';
import '../libraries/Base64.sol';
/// @title PlanetsModule
/// @author Simon Fremaux (@dievardump)
contract PlanetsModule is
Ownable,
NFBaseModule,
INFModuleTokenURI,
INFModuleRenderTokenURI,
INFModuleWithRoyalties
{
// using ECDSA for bytes32;
using Strings for uint256;
using Randomize for Randomize.Random;
uint256 constant SEED_BOUND = 1000000000;
// emitted when planets are claimed
event PlanetsClaimed(uint256[] tokenIds);
// contract actually holding the planets
address public planetsContract;
// astraglade contract to claim ids from
address public astragladeContract;
// contract operator next to the owner
address public contractOperator =
address(0xD1edDfcc4596CC8bD0bd7495beaB9B979fc50336);
// project base render URI
string private _baseRenderURI;
// whenever all images are uploaded on arweave/ipfs and
// this flag allows to stop all update of images, scripts etc...
bool public frozenMeta;
// base image rendering URI
// before all Planets are minted, images will be stored on our servers since
// they need to be generated after minting
// after all planets are minted, they will all be stored in a decentralized way
// and the _baseImagesURI will be updated
string private _baseImagesURI;
// project description
string internal _description;
address[3] public feeRecipients = [
0xe4657aF058E3f844919c3ee713DF09c3F2949447,
0xb275E5aa8011eA32506a91449B190213224aEc1e,
0xdAC81C3642b520584eD0E743729F238D1c350E62
];
mapping(uint256 => bytes32) public planetSeed;
// saving already taken seeds to ensure not reusing a seed
mapping(uint256 => bool) public seedTaken;
modifier onlyOperator() {
require(isOperator(msg.sender), 'Not operator.');
_;
}
function isOperator(address operator) public view returns (bool) {
return owner() == operator || contractOperator == operator;
}
/// @dev Receive, for royalties
receive() external payable {}
/// @notice constructor
/// @param contractURI_ The contract URI (containing its metadata) - can be empty ""
/// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer)
/// @param astragladeContract_ the contract holding the astraglades
constructor(
string memory contractURI_,
address owner_,
address planetsContract_,
address astragladeContract_
) NFBaseModule(contractURI_) {
planetsContract = planetsContract_;
astragladeContract = astragladeContract_;
if (address(0) != owner_) {
transferOwnership(owner_);
}
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return
interfaceId == type(INFModuleTokenURI).interfaceId ||
interfaceId == type(INFModuleRenderTokenURI).interfaceId ||
interfaceId == type(INFModuleWithRoyalties).interfaceId ||
super.supportsInterface(interfaceId);
}
/// @inheritdoc INFModuleWithRoyalties
function royaltyInfo(uint256 tokenId)
public
view
override
returns (address, uint256)
{
return royaltyInfo(msg.sender, tokenId);
}
/// @inheritdoc INFModuleWithRoyalties
function royaltyInfo(address, uint256)
public
view
override
returns (address receiver, uint256 basisPoint)
{
receiver = address(this);
basisPoint = 1000;
}
/// @inheritdoc INFModuleTokenURI
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
return tokenURI(msg.sender, tokenId);
}
/// @inheritdoc INFModuleTokenURI
function tokenURI(address, uint256 tokenId)
public
view
override
returns (string memory)
{
(
uint256 seed,
uint256 astragladeSeed,
uint256[] memory attributes
) = getPlanetData(tokenId);
return
string(
abi.encodePacked(
'data:application/json;base64,',
Base64.encode(
abi.encodePacked(
'{"name":"Planet - ',
tokenId.toString(),
'","license":"CC BY-SA 4.0","description":"',
getDescription(),
'","created_by":"Fabin Rasheed","twitter":"@astraglade","image":"',
abi.encodePacked(
getBaseImageURI(),
tokenId.toString()
),
'","seed":"',
seed.toString(),
abi.encodePacked(
'","astragladeSeed":"',
astragladeSeed.toString(),
'","attributes":[',
_generateJSONAttributes(attributes),
'],"animation_url":"',
_renderTokenURI(
seed,
astragladeSeed,
attributes
),
'"}'
)
)
)
)
);
}
/// @notice function that returns a string that can be used to render the current token
/// @param tokenId tokenId
/// @return the URI to render token
function renderTokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
return renderTokenURI(msg.sender, tokenId);
}
/// @notice function that returns a string that can be used to render the current token
/// @param tokenId tokenId
/// @return the URI to render token
function renderTokenURI(address, uint256 tokenId)
public
view
override
returns (string memory)
{
(
uint256 seed,
uint256 astragladeSeed,
uint256[] memory attributes
) = getPlanetData(tokenId);
return _renderTokenURI(seed, astragladeSeed, attributes);
}
/// @notice Helper returning all data for a Planet
/// @param tokenId the planet id
/// @return the planet seed, the astraglade seed and the planet attributes (the integer form)
function getPlanetData(uint256 tokenId)
public
view
returns (
uint256,
uint256,
uint256[] memory
)
{
require(planetSeed[tokenId] != 0, '!UNKNOWN_TOKEN!');
uint256 seed = uint256(planetSeed[tokenId]) % SEED_BOUND;
uint256[] memory attributes = _getAttributes(seed);
AstragladeUpgrade.AstragladeMeta memory astraglade = AstragladeUpgrade(
payable(astragladeContract)
).getAstraglade(tokenId);
return (seed, astraglade.seed, attributes);
}
/// @notice Returns Metadata for Astraglade id
/// @param tokenId the tokenId we want metadata for
function getAstraglade(uint256 tokenId)
public
view
returns (AstragladeUpgrade.AstragladeMeta memory astraglade)
{
return
AstragladeUpgrade(payable(astragladeContract)).getAstraglade(
tokenId
);
}
/// @notice helper to get the description
function getDescription() public view returns (string memory) {
if (bytes(_description).length == 0) {
return
"Astraglade Planets is an extension of project Astraglade (https://nurecas.com/astraglade). Planets are an interactive and generative 3D art that can be minted for free by anyone who owns an astraglade at [https://astraglade.beyondnft.io/planets/](https://astraglade.beyondnft.io/planets/). When a Planet is minted, the owner's astraglade will orbit forever around the planet that they mint.";
}
return _description;
}
/// @notice helper to get the baseRenderURI
function getBaseRenderURI() public view returns (string memory) {
if (bytes(_baseRenderURI).length == 0) {
return 'ar://JYtFvtxlpyur2Cdpaodmo46XzuTpmp0OwJl13rFUrrg/';
}
return _baseRenderURI;
}
/// @notice helper to get the baseImageURI
function getBaseImageURI() public view returns (string memory) {
if (bytes(_baseImagesURI).length == 0) {
return 'https://astraglade-api.beyondnft.io/planets/images/';
}
return _baseImagesURI;
}
/// @inheritdoc INFModule
function onAttach()
external
virtual
override(INFModule, NFBaseModule)
returns (bool)
{
// only the first attach is accepted, saves a "setPlanetsContract" call
if (planetsContract == address(0)) {
planetsContract = msg.sender;
return true;
}
return false;
}
/// @notice Claim tokenIds[] from the astraglade contract
/// @param tokenIds the tokenIds to claim
function claim(uint256[] calldata tokenIds) external {
address operator = msg.sender;
// saves some reads
address astragladeContract_ = astragladeContract;
address planetsContract_ = planetsContract;
for (uint256 i; i < tokenIds.length; i++) {
_claim(
operator,
tokenIds[i],
astragladeContract_,
planetsContract_
);
}
}
/// @notice Allows to freeze any metadata update
function freezeMeta() external onlyOperator {
frozenMeta = true;
}
/// @notice sets contract uri
/// @param newURI the new uri
function setContractURI(string memory newURI) external onlyOperator {
_setContractURI(newURI);
}
/// @notice sets planets contract
/// @param planetsContract_ the contract containing planets
function setPlanetsContract(address planetsContract_)
external
onlyOperator
{
planetsContract = planetsContract_;
}
/// @notice helper to set the description
/// @param newDescription the new description
function setDescription(string memory newDescription)
external
onlyOperator
{
require(frozenMeta == false, '!META_FROZEN!');
_description = newDescription;
}
/// @notice helper to set the baseRenderURI
/// @param newRenderURI the new renderURI
function setBaseRenderURI(string memory newRenderURI)
external
onlyOperator
{
require(frozenMeta == false, '!META_FROZEN!');
_baseRenderURI = newRenderURI;
}
/// @notice helper to set the baseImageURI
/// @param newBaseImagesURI the new base image URI
function setBaseImagesURI(string memory newBaseImagesURI)
external
onlyOperator
{
require(frozenMeta == false, '!META_FROZEN!');
_baseImagesURI = newBaseImagesURI;
}
/// @dev Owner withdraw balance function
function withdraw() external onlyOperator {
address[3] memory feeRecipients_ = feeRecipients;
uint256 balance_ = address(this).balance;
payable(address(feeRecipients_[0])).transfer((balance_ * 30) / 100);
payable(address(feeRecipients_[1])).transfer((balance_ * 35) / 100);
payable(address(feeRecipients_[2])).transfer(address(this).balance);
}
/// @notice helper to set the fee recipient at `index`
/// @param newFeeRecipient the new address
/// @param index the index to edit
function setFeeRecipient(address newFeeRecipient, uint8 index)
external
onlyOperator
{
require(index < feeRecipients.length, '!INDEX_OVERFLOW!');
require(newFeeRecipient != address(0), '!INVALID_ADDRESS!');
feeRecipients[index] = newFeeRecipient;
}
/// @notice Helper for an operator to change the current operator address
/// @param newOperator the new operator
function setContractOperator(address newOperator) external onlyOperator {
contractOperator = newOperator;
}
/// @dev Allows to claim a tokenId; the Planet will always be minted to the owner of the Astraglade
/// @param operator the one launching the claim (needs to be owner or approved on the Astraglade)
/// @param tokenId the Astraglade tokenId to claim
/// @param astragladeContract_ the Astraglade contract to check ownership
/// @param planetsContract_ the Planet contract (where to mint the tokens)
function _claim(
address operator,
uint256 tokenId,
address astragladeContract_,
address planetsContract_
) internal {
AstragladeUpgrade astraglade = AstragladeUpgrade(
payable(astragladeContract_)
);
address owner_ = astraglade.ownerOf(tokenId);
// verify that the operator has the right to claim
require(
owner_ == operator ||
astraglade.isApprovedForAll(owner_, operator) ||
astraglade.getApproved(tokenId) == operator,
'!NOT_AUTHORIZED!'
);
// mint
INiftyForge721 planets = INiftyForge721(planetsContract_);
// always mint to owner_, not to operator
planets.mint(owner_, '', tokenId, address(0), 0, address(0));
// creates a seed
bytes32 seed;
do {
seed = _generateSeed(
tokenId,
block.timestamp,
owner_,
blockhash(block.number - 1)
);
} while (seedTaken[uint256(seed) % SEED_BOUND]);
planetSeed[tokenId] = seed;
// ensure we won't have two seeds rendering the same planet
seedTaken[uint256(seed) % SEED_BOUND] = true;
}
/// @dev Calculate next seed using a few on chain data
/// @param tokenId tokenId
/// @param timestamp current block timestamp
/// @param operator current operator
/// @param blockHash last block hash
/// @return a new bytes32 seed
function _generateSeed(
uint256 tokenId,
uint256 timestamp,
address operator,
bytes32 blockHash
) internal view returns (bytes32) {
return
keccak256(
abi.encodePacked(
tokenId,
timestamp,
operator,
blockHash,
block.coinbase,
block.difficulty,
tx.gasprice
)
);
}
/// @notice generates the attributes values according to seed
/// @param seed the seed to generate the values
/// @return attributes an array of attributes (integers)
function _getAttributes(uint256 seed)
internal
pure
returns (uint256[] memory attributes)
{
Randomize.Random memory random = Randomize.Random({seed: seed});
// remember, all numbers returned by randomBetween are
// multiplicated by 1000, because solidity has no decimals
// so we will divide all those numbers later
attributes = new uint256[](6);
// density
attributes[0] = random.randomBetween(10, 200);
// radius
attributes[1] = random.randomBetween(5, 15);
// cube planet
attributes[2] = random.randomBetween(0, 5000);
if (attributes[2] < 20000) {
// set radius = 10 if cube
attributes[1] = 10000;
}
// shade - remember to actually change 1 into -1 in the HTML
attributes[3] = random.randomBetween(0, 2) < 1000 ? 0 : 1;
// rings
// if cube, 2 or 3 rings
if (attributes[2] < 20000) {
attributes[4] = random.randomBetween(2, 4) / 1000;
} else {
// else 30% chances to have rings (1, 2 and 3)
attributes[4] = random.randomBetween(0, 10) / 1000;
// if more than 3, then none.
if (attributes[4] > 3) {
attributes[4] = 0;
}
}
// moons, 0, 1, 2 or 3
attributes[5] = random.randomBetween(0, 4) / 1000;
}
/// @notice Generates the JSON string from the attributes values
/// @param attributes the attributes values
/// @return jsonAttributes, the string for attributes
function _generateJSONAttributes(uint256[] memory attributes)
internal
pure
returns (string memory)
{
bytes memory coma = bytes(',');
// Terrain
bytes memory jsonAttributes = abi.encodePacked(
_makeAttributes(
'Terrain',
attributes[0] < 50000 ? 'Dense' : 'Sparse'
),
coma
);
// Size
if (attributes[1] < 8000) {
jsonAttributes = abi.encodePacked(
jsonAttributes,
_makeAttributes('Size', 'Tiny'),
coma
);
} else if (attributes[1] < 12000) {
jsonAttributes = abi.encodePacked(
jsonAttributes,
_makeAttributes('Size', 'Medium'),
coma
);
} else {
jsonAttributes = abi.encodePacked(
jsonAttributes,
_makeAttributes('Size', 'Giant'),
coma
);
}
// Form
jsonAttributes = abi.encodePacked(
jsonAttributes,
_makeAttributes(
'Form',
attributes[2] < 20000 ? 'Tesseract' : 'Geo'
),
coma,
_makeAttributes('Shade', attributes[3] == 0 ? 'Vibrant' : 'Simple'),
coma,
_makeAttributes('Rings', attributes[4].toString()),
coma,
_makeAttributes('Moons', attributes[5].toString())
);
return string(jsonAttributes);
}
function _makeAttributes(string memory name_, string memory value)
internal
pure
returns (bytes memory)
{
return
abi.encodePacked(
'{"trait_type":"',
name_,
'","value":"',
value,
'"}'
);
}
/// @notice returns the URL to render the Planet
/// @param seed the planet seed
/// @param astragladeSeed the astraglade seed
/// @param attributes all attributes needed for the planets
/// @return the URI to render the planet
function _renderTokenURI(
uint256 seed,
uint256 astragladeSeed,
uint256[] memory attributes
) internal view returns (string memory) {
bytes memory coma = bytes(',');
bytes memory attrs = abi.encodePacked(
attributes[0].toString(),
coma,
attributes[1].toString(),
coma,
attributes[2].toString(),
coma
);
return
string(
abi.encodePacked(
getBaseRenderURI(),
'?seed=',
seed.toString(),
'&astragladeSeed=',
astragladeSeed.toString(),
'&attributes=',
abi.encodePacked(
attrs,
attributes[3].toString(),
coma,
attributes[4].toString(),
coma,
attributes[5].toString()
)
)
);
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides a function for encoding some bytes in base64
library Base64 {
string internal constant TABLE =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return '';
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {
} lt(dataPtr, endPtr) {
} {
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(input, 0x3F))))
)
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
}
return result;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// small library to randomize using (min, max, seed)
// all number returned are considered with 3 decimals
library Randomize {
struct Random {
uint256 seed;
}
/// @notice This function uses seed to return a pseudo random interger between 0 and 1000
/// Because solidity has no decimal points, the number is considered to be [0, 0.999]
/// @param random the random seed
/// @return the pseudo random number (with 3 decimal basis)
function randomDec(Random memory random) internal pure returns (uint256) {
random.seed ^= random.seed << 13;
random.seed ^= random.seed >> 17;
random.seed ^= random.seed << 5;
return ((random.seed < 0 ? ~random.seed + 1 : random.seed) % 1000);
}
/// @notice return a number between [min, max[, multiplicated by 1000 (for 3 decimal basis)
/// @param random the random seed
/// @return the pseudo random number (with 3 decimal basis)
function randomBetween(
Random memory random,
uint256 min,
uint256 max
) internal pure returns (uint256) {
return min * 1000 + (max - min) * Randomize.randomDec(random);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol';
import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import '../ERC721Ownable.sol';
import '../ERC2981/IERC2981Royalties.sol';
import './IOldMetaHolder.sol';
/// @title AstragladeUpgrade
/// @author Simon Fremaux (@dievardump)
contract AstragladeUpgrade is
IERC2981Royalties,
ERC721Ownable,
IERC721Receiver
{
using ECDSA for bytes32;
using Strings for uint256;
// emitted when an Astraglade has been upgrade
event AstragladeUpgraded(address indexed operator, uint256 indexed tokenId);
// emitted when a token owner asks for a metadata update (image or signature)
// because of rendering error
event RequestUpdate(address indexed operator, uint256 indexed tokenId);
struct MintingOrder {
address to;
uint256 expiration;
uint256 seed;
string signature;
string imageHash;
}
struct AstragladeMeta {
uint256 seed;
string signature;
string imageHash;
}
// start at the old contract last token Id minted
uint256 public lastTokenId = 84;
// signer that signs minting orders
address public mintSigner;
// how long before an order expires
uint256 public expiration;
// old astraglade contract to allow upgrade to new token
address public oldAstragladeContract;
// contract that holds metadata of previous contract Astraglades
address public oldMetaHolder;
// contract operator next to the owner
address public contractOperator =
address(0xD1edDfcc4596CC8bD0bd7495beaB9B979fc50336);
// max supply
uint256 constant MAX_SUPPLY = 5555;
// price
uint256 constant PRICE = 0.0888 ether;
// project base render URI
string private _baseRenderURI;
// project description
string internal _description;
// list of Astraglades
mapping(uint256 => AstragladeMeta) internal _astraglades;
// saves if a minting order was already used or not
mapping(bytes32 => uint256) public messageToTokenId;
// request updates
mapping(uint256 => bool) public requestUpdates;
// remaining giveaways
uint256 public remainingGiveaways = 100;
// user giveaways
mapping(address => uint8) public giveaways;
// Petri already redeemed
mapping(uint256 => bool) public petriRedeemed;
address public artBlocks;
address[3] public feeRecipients = [
0xe4657aF058E3f844919c3ee713DF09c3F2949447,
0xb275E5aa8011eA32506a91449B190213224aEc1e,
0xdAC81C3642b520584eD0E743729F238D1c350E62
];
modifier onlyOperator() {
require(isOperator(msg.sender), 'Not operator.');
_;
}
function isOperator(address operator) public view returns (bool) {
return owner() == operator || contractOperator == operator;
}
/// @notice constructor
/// @param name_ name of the contract (see ERC721)
/// @param symbol_ symbol of the contract (see ERC721)
/// @param contractURI_ The contract URI (containing its metadata) - can be empty ""
/// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0)
/// @param mintSigner_ Address of the wallet used to sign minting orders
/// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer)
constructor(
string memory name_,
string memory symbol_,
string memory contractURI_,
address openseaProxyRegistry_,
address mintSigner_,
address owner_,
address oldAstragladeContract_,
address oldMetaHolder_,
address artBlocks_
)
ERC721Ownable(
name_,
symbol_,
contractURI_,
openseaProxyRegistry_,
owner_
)
{
mintSigner = mintSigner_;
oldAstragladeContract = oldAstragladeContract_;
oldMetaHolder = oldMetaHolder_;
artBlocks = artBlocks_;
}
/// @notice Mint one token using a minting order
/// @dev mintingSignature must be a signature that matches `mintSigner` for `mintingOrder`
/// @param mintingOrder the minting order
/// @param mintingSignature signature for the mintingOrder
/// @param petriId petri id to redeem if owner and not already redeemed the free AG
function mint(
MintingOrder memory mintingOrder,
bytes memory mintingSignature,
uint256 petriId
) external payable {
bytes32 message = hashMintingOrder(mintingOrder)
.toEthSignedMessageHash();
address sender = msg.sender;
require(
message.recover(mintingSignature) == mintSigner,
'Wrong minting order signature.'
);
require(
mintingOrder.expiration >= block.timestamp,
'Minting order expired.'
);
require(
mintingOrder.to == sender,
'Minting order for another address.'
);
require(mintingOrder.seed != 0, 'Seed can not be 0');
require(messageToTokenId[message] == 0, 'Token already minted.');
uint256 tokenId = lastTokenId + 1;
require(tokenId <= MAX_SUPPLY, 'Max supply already reached.');
uint256 mintingCost = PRICE;
// For Each Petri (https://artblocks.io/project/67/) created by Fabin on artblocks.io
// the owner can claim a free Astraglade
// After a Petri was used, it CAN NOT be used again to claim another Astraglade
if (petriId >= 67000000 && petriId < 67000200) {
require(
// petri was not redeemed already
petriRedeemed[petriId] == false &&
// msg.sender is Petri owner
ERC721(artBlocks).ownerOf(petriId) == sender,
'Petri already redeemed or not owner'
);
petriRedeemed[petriId] = true;
mintingCost = 0;
} else if (giveaways[sender] > 0) {
// if the user has some free mints
giveaways[sender]--;
mintingCost = 0;
}
require(
msg.value == mintingCost || isOperator(sender),
'Incorrect value.'
);
lastTokenId = tokenId;
messageToTokenId[message] = tokenId;
_astraglades[tokenId] = AstragladeMeta({
seed: mintingOrder.seed,
signature: mintingOrder.signature,
imageHash: mintingOrder.imageHash
});
_safeMint(mintingOrder.to, tokenId, '');
}
/// @inheritdoc ERC165
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return
ERC721Enumerable.supportsInterface(interfaceId) ||
interfaceId == type(IERC2981Royalties).interfaceId;
}
/// @notice Helper to get the price
/// @return the price to mint
function getPrice() external pure returns (uint256) {
return PRICE;
}
/// @notice tokenURI override that returns a data:json application
/// @inheritdoc ERC721
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
AstragladeMeta memory astraglade = getAstraglade(tokenId);
string memory astraType;
if (tokenId <= 10) {
astraType = 'Universa';
} else if (tokenId <= 100) {
astraType = 'Galactica';
} else if (tokenId <= 1000) {
astraType = 'Nebula';
} else if (tokenId <= 2500) {
astraType = 'Meteora';
} else if (tokenId <= 5554) {
astraType = 'Solaris';
} else {
astraType = 'Quanta';
}
return
string(
abi.encodePacked(
'data:application/json;utf8,{"name":"Astraglade - ',
tokenId.toString(),
' - ',
astraType,
'","license":"CC BY-SA 4.0","description":"',
getDescription(),
'","created_by":"Fabin Rasheed","twitter":"@astraglade","image":"ipfs://ipfs/',
astraglade.imageHash,
'","seed":"',
astraglade.seed.toString(),
'","signature":"',
astraglade.signature,
'","animation_url":"',
renderTokenURI(tokenId),
'"}'
)
);
}
/// @notice function that returns a string that can be used to render the current token
/// @param tokenId tokenId
/// @return the URI to render token
function renderTokenURI(uint256 tokenId)
public
view
returns (string memory)
{
AstragladeMeta memory astraglade = getAstraglade(tokenId);
return
string(
abi.encodePacked(
getBaseRenderURI(),
'?seed=',
astraglade.seed.toString(),
'&signature=',
astraglade.signature
)
);
}
/// @notice Returns Metadata for Astraglade id
/// @param tokenId the tokenId we want metadata for
function getAstraglade(uint256 tokenId)
public
view
returns (AstragladeMeta memory astraglade)
{
require(_exists(tokenId), 'Astraglade: nonexistent token');
// if the metadata are in this contract
if (_astraglades[tokenId].seed != 0) {
astraglade = _astraglades[tokenId];
} else {
// or in the old one
(
uint256 seed,
string memory signature,
string memory imageHash
) = IOldMetaHolder(oldMetaHolder).get(tokenId);
astraglade.seed = seed;
astraglade.signature = signature;
astraglade.imageHash = imageHash;
}
}
/// @notice helper to get the description
function getDescription() public view returns (string memory) {
if (bytes(_description).length == 0) {
return
'Astraglade is an interactive, generative, 3D collectible project. Astraglades are collected through a unique social collection mechanism. Each version of Astraglade can be signed with a signature which will remain in the artwork forever.';
}
return _description;
}
/// @notice helper to set the description
/// @param newDescription the new description
function setDescription(string memory newDescription)
external
onlyOperator
{
_description = newDescription;
}
/// @notice helper to get the base expiration time
function getExpiration() public view returns (uint256) {
if (expiration == 0) {
return 15 * 60;
}
return expiration;
}
/// @notice helper to set the expiration
/// @param newExpiration the new expiration
function setExpiration(uint256 newExpiration) external onlyOperator {
expiration = newExpiration;
}
/// @notice helper to get the baseRenderURI
function getBaseRenderURI() public view returns (string memory) {
if (bytes(_baseRenderURI).length == 0) {
return 'ipfs://ipfs/QmP85DSrtLAxSBnct9iUr7qNca43F3E4vuG6Jv5aoTh9w7';
}
return _baseRenderURI;
}
/// @notice helper to set the baseRenderURI
/// @param newRenderURI the new renderURI
function setBaseRenderURI(string memory newRenderURI)
external
onlyOperator
{
_baseRenderURI = newRenderURI;
}
/// @notice Helper to do giveaways - there can only be `remainingGiveaways` giveaways given all together
/// @param winner the giveaway winner
/// @param count how many we giveaway to recipient
function giveaway(address winner, uint8 count) external onlyOperator {
require(remainingGiveaways >= count, 'Giveaway limit reached');
remainingGiveaways -= count;
giveaways[winner] += count;
}
/// @dev Receive, for royalties
receive() external payable {}
/// @dev Owner withdraw balance function
function withdraw() external onlyOperator {
address[3] memory feeRecipients_ = feeRecipients;
uint256 balance_ = address(this).balance;
payable(address(feeRecipients_[0])).transfer((balance_ * 30) / 100);
payable(address(feeRecipients_[1])).transfer((balance_ * 35) / 100);
payable(address(feeRecipients_[2])).transfer(address(this).balance);
}
/// @notice helper to set the fee recipient at `index`
/// @param newFeeRecipient the new address
/// @param index the index to edit
function setFeeRecipient(address newFeeRecipient, uint8 index)
external
onlyOperator
{
require(index < feeRecipients.length, 'Index too high.');
require(newFeeRecipient != address(0), 'Invalid address.');
feeRecipients[index] = newFeeRecipient;
}
/// @notice 10% royalties going to this contract
/// @inheritdoc IERC2981Royalties
function royaltyInfo(uint256, uint256 value)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
receiver = address(this);
royaltyAmount = (value * 1000) / 10000;
}
/// @notice Hash the Minting Order so it can be signed by the signer
/// @param mintingOrder the minting order
/// @return the hash to sign
function hashMintingOrder(MintingOrder memory mintingOrder)
public
pure
returns (bytes32)
{
return keccak256(abi.encode(mintingOrder));
}
/// @notice Helper for the owner to change current minting signer
/// @dev needs to be owner
/// @param mintSigner_ new signer
function setMintingSigner(address mintSigner_) external onlyOperator {
require(mintSigner_ != address(0), 'Invalid Signer address.');
mintSigner = mintSigner_;
}
/// @notice Helper for an operator to change the current operator address
/// @param newOperator the new operator
function setContractOperator(address newOperator) external onlyOperator {
contractOperator = newOperator;
}
/// @notice Helper for the owner to change the oldMetaHolder
/// @dev needs to be owner
/// @param oldMetaHolder_ new oldMetaHolder address
function setOldMetaHolder(address oldMetaHolder_) external onlyOperator {
require(oldMetaHolder_ != address(0), 'Invalid Contract address.');
oldMetaHolder = oldMetaHolder_;
}
/// @notice Helpers that returns the MintingOrder plus the message to sign
/// @param to the address of the creator
/// @param seed the seed
/// @param signature the signature
/// @param imageHash image hash
/// @return mintingOrder and message to hash
function createMintingOrder(
address to,
uint256 seed,
string memory signature,
string memory imageHash
)
external
view
returns (MintingOrder memory mintingOrder, bytes32 message)
{
mintingOrder = MintingOrder({
to: to,
expiration: block.timestamp + getExpiration(),
seed: seed,
signature: signature,
imageHash: imageHash
});
message = hashMintingOrder(mintingOrder);
}
/// @notice returns a tokenId from an mintingOrder, used to know if already minted
/// @param mintingOrder the minting order to check
/// @return an integer. 0 if not minted, else the tokenId
function tokenIdFromOrder(MintingOrder memory mintingOrder)
external
view
returns (uint256)
{
bytes32 message = hashMintingOrder(mintingOrder)
.toEthSignedMessageHash();
return messageToTokenId[message];
}
/// @notice Allows an owner to request a metadata update.
/// Because Astraglade are generated from a backend it can happen that a bug
/// blocks the generation of the image OR that a signature with special characters stops the
/// token from working.
/// This method allows a user to ask for regeneration of the image / signature update
/// A contract operator can then update imageHash and / or signature
/// @param tokenId the tokenId to update
function requestMetaUpdate(uint256 tokenId) external {
require(ownerOf(tokenId) == msg.sender, 'Not token owner.');
requestUpdates[tokenId] = true;
emit RequestUpdate(msg.sender, tokenId);
}
/// @notice Allows an operator of this contract to update a tokenId metadata (signature or image hash)
/// after it was requested by its owner.
/// This is only used in the case the generation of the Preview image did fail
/// in some way or if the signature has special characters that stops the token from working
/// @param tokenId the tokenId to update
/// @param newImageHash the new imageHash (can be empty)
/// @param newSignature the new signature (can be empty)
function updateMeta(
uint256 tokenId,
string memory newImageHash,
string memory newSignature
) external onlyOperator {
require(
requestUpdates[tokenId] == true,
'No update request for token.'
);
requestUpdates[tokenId] = false;
// get the current Astraglade data
// for ids 1-82 it can come from oldMetaHolder
AstragladeMeta memory astraglade = getAstraglade(tokenId);
if (bytes(newImageHash).length > 0) {
astraglade.imageHash = newImageHash;
}
if (bytes(newSignature).length > 0) {
astraglade.signature = newSignature;
}
// save the new state
_astraglades[tokenId] = astraglade;
}
/// @notice function used to allow upgrade of old contract Astraglade to this one.
/// @inheritdoc IERC721Receiver
function onERC721Received(
address,
address from,
uint256 tokenId,
bytes calldata
) external override returns (bytes4) {
require(msg.sender == oldAstragladeContract, 'Only old Astraglades.');
// mint tokenId to from
_mint(from, tokenId);
// burn old tokenId
ERC721Burnable(msg.sender).burn(tokenId);
emit AstragladeUpgraded(from, tokenId);
return 0x150b7a02;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IOldMetaHolder
/// @author Simon Fremaux (@dievardump)
interface IOldMetaHolder {
function get(uint256 tokenId)
external
pure
returns (
uint256,
string memory,
string memory
);
}
|
function used to allow upgrade of old contract Astraglade to this one. @inheritdoc IERC721Receiver mint tokenId to from burn old tokenId
|
function onERC721Received(
address,
address from,
uint256 tokenId,
bytes calldata
) external override returns (bytes4) {
require(msg.sender == oldAstragladeContract, 'Only old Astraglades.');
_mint(from, tokenId);
ERC721Burnable(msg.sender).burn(tokenId);
emit AstragladeUpgraded(from, tokenId);
return 0x150b7a02;
}
| 164,237 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../interfaces/IAccessControl.sol";
/**
* @dev This contract is fully forked from OpenZeppelin `AccessControlUpgradeable`.
* The only difference is the removal of the ERC165 implementation as it's not
* needed in Angle.
*
* Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, IAccessControl {
function __AccessControl_init() internal initializer {
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, msg.sender);
_;
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external override {
require(account == msg.sender, "71");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) internal {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, msg.sender);
}
}
function _revokeRole(bytes32 role, address account) internal {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, msg.sender);
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
/// @title IAccessControl
/// @author Forked from OpenZeppelin
/// @notice Interface for `AccessControl` contracts
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
/// @title IAgToken
/// @author Angle Core Team
/// @notice Interface for the stablecoins `AgToken` contracts
/// @dev The only functions that are left in the interface are the functions which are used
/// at another point in the protocol by a different contract
interface IAgToken is IERC20Upgradeable {
// ======================= `StableMaster` functions ============================
function mint(address account, uint256 amount) external;
function burnFrom(
uint256 amount,
address burner,
address sender
) external;
function burnSelf(uint256 amount, address burner) external;
// ========================= External function =================================
function stableMaster() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
/// @title ICollateralSettler
/// @author Angle Core Team
/// @notice Interface for the collateral settlement contracts
interface ICollateralSettler {
function triggerSettlement(
uint256 _oracleValue,
uint256 _sanRate,
uint256 _stocksUsers
) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "./IStableMaster.sol";
/// @title ICore
/// @author Angle Core Team
/// @dev Interface for the functions of the `Core` contract
interface ICore {
function revokeStableMaster(address stableMaster) external;
function addGovernor(address _governor) external;
function removeGovernor(address _governor) external;
function setGuardian(address _guardian) external;
function revokeGuardian() external;
function governorList() external view returns (address[] memory);
function stablecoinList() external view returns (address[] memory);
function guardian() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
interface IERC721 is IERC165 {
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
interface IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "./IAccessControl.sol";
/// @title IFeeManagerFunctions
/// @author Angle Core Team
/// @dev Interface for the `FeeManager` contract
interface IFeeManagerFunctions is IAccessControl {
// ================================= Keepers ===================================
function updateUsersSLP() external;
function updateHA() external;
// ================================= Governance ================================
function deployCollateral(
address[] memory governorList,
address guardian,
address _perpetualManager
) external;
function setFees(
uint256[] memory xArray,
uint64[] memory yArray,
uint8 typeChange
) external;
function setHAFees(uint64 _haFeeDeposit, uint64 _haFeeWithdraw) external;
}
/// @title IFeeManager
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables and mappings
/// @dev We need these getters as they are used in other contracts of the protocol
interface IFeeManager is IFeeManagerFunctions {
function stableMaster() external view returns (address);
function perpetualManager() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
/// @title IOracle
/// @author Angle Core Team
/// @notice Interface for Angle's oracle contracts reading oracle rates from both UniswapV3 and Chainlink
/// from just UniswapV3 or from just Chainlink
interface IOracle {
function read() external view returns (uint256);
function readAll() external view returns (uint256 lowerRate, uint256 upperRate);
function readLower() external view returns (uint256);
function readUpper() external view returns (uint256);
function readQuote(uint256 baseAmount) external view returns (uint256);
function readQuoteLower(uint256 baseAmount) external view returns (uint256);
function inBase() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "./IERC721.sol";
import "./IFeeManager.sol";
import "./IOracle.sol";
import "./IAccessControl.sol";
/// @title Interface of the contract managing perpetuals
/// @author Angle Core Team
/// @dev Front interface, meaning only user-facing functions
interface IPerpetualManagerFront is IERC721Metadata {
function openPerpetual(
address owner,
uint256 amountBrought,
uint256 amountCommitted,
uint256 maxOracleRate,
uint256 minNetMargin
) external returns (uint256 perpetualID);
function closePerpetual(
uint256 perpetualID,
address to,
uint256 minCashOutAmount
) external;
function addToPerpetual(uint256 perpetualID, uint256 amount) external;
function removeFromPerpetual(
uint256 perpetualID,
uint256 amount,
address to
) external;
function liquidatePerpetuals(uint256[] memory perpetualIDs) external;
function forceClosePerpetuals(uint256[] memory perpetualIDs) external;
// ========================= External View Functions =============================
function getCashOutAmount(uint256 perpetualID, uint256 rate) external view returns (uint256, uint256);
function isApprovedOrOwner(address spender, uint256 perpetualID) external view returns (bool);
}
/// @title Interface of the contract managing perpetuals
/// @author Angle Core Team
/// @dev This interface does not contain user facing functions, it just has functions that are
/// interacted with in other parts of the protocol
interface IPerpetualManagerFunctions is IAccessControl {
// ================================= Governance ================================
function deployCollateral(
address[] memory governorList,
address guardian,
IFeeManager feeManager,
IOracle oracle_
) external;
function setFeeManager(IFeeManager feeManager_) external;
function setHAFees(
uint64[] memory _xHAFees,
uint64[] memory _yHAFees,
uint8 deposit
) external;
function setTargetAndLimitHAHedge(uint64 _targetHAHedge, uint64 _limitHAHedge) external;
function setKeeperFeesLiquidationRatio(uint64 _keeperFeesLiquidationRatio) external;
function setKeeperFeesCap(uint256 _keeperFeesLiquidationCap, uint256 _keeperFeesClosingCap) external;
function setKeeperFeesClosing(uint64[] memory _xKeeperFeesClosing, uint64[] memory _yKeeperFeesClosing) external;
function setLockTime(uint64 _lockTime) external;
function setBoundsPerpetual(uint64 _maxLeverage, uint64 _maintenanceMargin) external;
function pause() external;
function unpause() external;
// ==================================== Keepers ================================
function setFeeKeeper(uint64 feeDeposit, uint64 feesWithdraw) external;
// =============================== StableMaster ================================
function setOracle(IOracle _oracle) external;
}
/// @title IPerpetualManager
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables
interface IPerpetualManager is IPerpetualManagerFunctions {
function poolManager() external view returns (address);
function oracle() external view returns (address);
function targetHAHedge() external view returns (uint64);
function totalHedgeAmount() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "./IFeeManager.sol";
import "./IPerpetualManager.sol";
import "./IOracle.sol";
// Struct for the parameters associated to a strategy interacting with a collateral `PoolManager`
// contract
struct StrategyParams {
// Timestamp of last report made by this strategy
// It is also used to check if a strategy has been initialized
uint256 lastReport;
// Total amount the strategy is expected to have
uint256 totalStrategyDebt;
// The share of the total assets in the `PoolManager` contract that the `strategy` can access to.
uint256 debtRatio;
}
/// @title IPoolManagerFunctions
/// @author Angle Core Team
/// @notice Interface for the collateral poolManager contracts handling each one type of collateral for
/// a given stablecoin
/// @dev Only the functions used in other contracts of the protocol are left here
interface IPoolManagerFunctions {
// ============================ Constructor ====================================
function deployCollateral(
address[] memory governorList,
address guardian,
IPerpetualManager _perpetualManager,
IFeeManager feeManager,
IOracle oracle
) external;
// ============================ Yield Farming ==================================
function creditAvailable() external view returns (uint256);
function debtOutstanding() external view returns (uint256);
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external;
// ============================ Governance =====================================
function addGovernor(address _governor) external;
function removeGovernor(address _governor) external;
function setGuardian(address _guardian, address guardian) external;
function revokeGuardian(address guardian) external;
function setFeeManager(IFeeManager _feeManager) external;
// ============================= Getters =======================================
function getBalance() external view returns (uint256);
function getTotalAsset() external view returns (uint256);
}
/// @title IPoolManager
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables and mappings
/// @dev Used in other contracts of the protocol
interface IPoolManager is IPoolManagerFunctions {
function stableMaster() external view returns (address);
function perpetualManager() external view returns (address);
function token() external view returns (address);
function feeManager() external view returns (address);
function totalDebt() external view returns (uint256);
function strategies(address _strategy) external view returns (StrategyParams memory);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
/// @title ISanToken
/// @author Angle Core Team
/// @notice Interface for Angle's `SanToken` contract that handles sanTokens, tokens that are given to SLPs
/// contributing to a collateral for a given stablecoin
interface ISanToken is IERC20Upgradeable {
// ================================== StableMaster =============================
function mint(address account, uint256 amount) external;
function burnFrom(
uint256 amount,
address burner,
address sender
) external;
function burnSelf(uint256 amount, address burner) external;
function stableMaster() external view returns (address);
function poolManager() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// Normally just importing `IPoolManager` should be sufficient, but for clarity here
// we prefer to import all concerned interfaces
import "./IPoolManager.sol";
import "./IOracle.sol";
import "./IPerpetualManager.sol";
import "./ISanToken.sol";
// Struct to handle all the parameters to manage the fees
// related to a given collateral pool (associated to the stablecoin)
struct MintBurnData {
// Values of the thresholds to compute the minting fees
// depending on HA hedge (scaled by `BASE_PARAMS`)
uint64[] xFeeMint;
// Values of the fees at thresholds (scaled by `BASE_PARAMS`)
uint64[] yFeeMint;
// Values of the thresholds to compute the burning fees
// depending on HA hedge (scaled by `BASE_PARAMS`)
uint64[] xFeeBurn;
// Values of the fees at thresholds (scaled by `BASE_PARAMS`)
uint64[] yFeeBurn;
// Max proportion of collateral from users that can be covered by HAs
// It is exactly the same as the parameter of the same name in `PerpetualManager`, whenever one is updated
// the other changes accordingly
uint64 targetHAHedge;
// Minting fees correction set by the `FeeManager` contract: they are going to be multiplied
// to the value of the fees computed using the hedge curve
// Scaled by `BASE_PARAMS`
uint64 bonusMalusMint;
// Burning fees correction set by the `FeeManager` contract: they are going to be multiplied
// to the value of the fees computed using the hedge curve
// Scaled by `BASE_PARAMS`
uint64 bonusMalusBurn;
// Parameter used to limit the number of stablecoins that can be issued using the concerned collateral
uint256 capOnStableMinted;
}
// Struct to handle all the variables and parameters to handle SLPs in the protocol
// including the fraction of interests they receive or the fees to be distributed to
// them
struct SLPData {
// Last timestamp at which the `sanRate` has been updated for SLPs
uint256 lastBlockUpdated;
// Fees accumulated from previous blocks and to be distributed to SLPs
uint256 lockedInterests;
// Max interests used to update the `sanRate` in a single block
// Should be in collateral token base
uint256 maxInterestsDistributed;
// Amount of fees left aside for SLPs and that will be distributed
// when the protocol is collateralized back again
uint256 feesAside;
// Part of the fees normally going to SLPs that is left aside
// before the protocol is collateralized back again (depends on collateral ratio)
// Updated by keepers and scaled by `BASE_PARAMS`
uint64 slippageFee;
// Portion of the fees from users minting and burning
// that goes to SLPs (the rest goes to surplus)
uint64 feesForSLPs;
// Slippage factor that's applied to SLPs exiting (depends on collateral ratio)
// If `slippage = BASE_PARAMS`, SLPs can get nothing, if `slippage = 0` they get their full claim
// Updated by keepers and scaled by `BASE_PARAMS`
uint64 slippage;
// Portion of the interests from lending
// that goes to SLPs (the rest goes to surplus)
uint64 interestsForSLPs;
}
/// @title IStableMasterFunctions
/// @author Angle Core Team
/// @notice Interface for the `StableMaster` contract
interface IStableMasterFunctions {
function deploy(
address[] memory _governorList,
address _guardian,
address _agToken
) external;
// ============================== Lending ======================================
function accumulateInterest(uint256 gain) external;
function signalLoss(uint256 loss) external;
// ============================== HAs ==========================================
function getStocksUsers() external view returns (uint256 maxCAmountInStable);
function convertToSLP(uint256 amount, address user) external;
// ============================== Keepers ======================================
function getCollateralRatio() external returns (uint256);
function setFeeKeeper(
uint64 feeMint,
uint64 feeBurn,
uint64 _slippage,
uint64 _slippageFee
) external;
// ============================== AgToken ======================================
function updateStocksUsers(uint256 amount, address poolManager) external;
// ============================= Governance ====================================
function setCore(address newCore) external;
function addGovernor(address _governor) external;
function removeGovernor(address _governor) external;
function setGuardian(address newGuardian, address oldGuardian) external;
function revokeGuardian(address oldGuardian) external;
function setCapOnStableAndMaxInterests(
uint256 _capOnStableMinted,
uint256 _maxInterestsDistributed,
IPoolManager poolManager
) external;
function setIncentivesForSLPs(
uint64 _feesForSLPs,
uint64 _interestsForSLPs,
IPoolManager poolManager
) external;
function setUserFees(
IPoolManager poolManager,
uint64[] memory _xFee,
uint64[] memory _yFee,
uint8 _mint
) external;
function setTargetHAHedge(uint64 _targetHAHedge) external;
function pause(bytes32 agent, IPoolManager poolManager) external;
function unpause(bytes32 agent, IPoolManager poolManager) external;
}
/// @title IStableMaster
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables and mappings
interface IStableMaster is IStableMasterFunctions {
function agToken() external view returns (address);
function collateralMap(IPoolManager poolManager)
external
view
returns (
IERC20 token,
ISanToken sanToken,
IPerpetualManager perpetualManager,
IOracle oracle,
uint256 stocksUsers,
uint256 sanRate,
uint256 collatBase,
SLPData memory slpData,
MintBurnData memory feeData
);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "./StableMasterInternal.sol";
/// @title StableMaster
/// @author Angle Core Team
/// @notice `StableMaster` is the contract handling all the collateral types accepted for a given stablecoin
/// It does all the accounting and is the point of entry in the protocol for stable holders and seekers as well as SLPs
/// @dev This file contains the core functions of the `StableMaster` contract
contract StableMaster is StableMasterInternal, IStableMasterFunctions, AccessControlUpgradeable {
using SafeERC20 for IERC20;
/// @notice Role for governors only
bytes32 public constant GOVERNOR_ROLE = keccak256("GOVERNOR_ROLE");
/// @notice Role for guardians and governors
bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE");
/// @notice Role for `Core` only, used to propagate guardian and governors
bytes32 public constant CORE_ROLE = keccak256("CORE_ROLE");
bytes32 public constant STABLE = keccak256("STABLE");
bytes32 public constant SLP = keccak256("SLP");
// ============================ DEPLOYER =======================================
/// @notice Creates the access control logic for the governor and guardian addresses
/// @param governorList List of the governor addresses of the protocol
/// @param guardian Guardian address of the protocol
/// @param _agToken Reference to the `AgToken`, that is the ERC20 token handled by the `StableMaster`
/// @dev This function is called by the `Core` when a stablecoin is deployed to maintain consistency
/// across the governor and guardian roles
/// @dev When this function is called by the `Core`, it has already been checked that the `stableMaster`
/// corresponding to the `agToken` was this `stableMaster`
function deploy(
address[] memory governorList,
address guardian,
address _agToken
) external override onlyRole(CORE_ROLE) {
for (uint256 i = 0; i < governorList.length; i++) {
_grantRole(GOVERNOR_ROLE, governorList[i]);
_grantRole(GUARDIAN_ROLE, governorList[i]);
}
_grantRole(GUARDIAN_ROLE, guardian);
agToken = IAgToken(_agToken);
// Since there is only one address that can be the `AgToken`, and since `AgToken`
// is not to be admin of any role, we do not define any access control role for it
}
// ============================ STRATEGIES =====================================
/// @notice Takes into account the gains made while lending and distributes it to SLPs by updating the `sanRate`
/// @param gain Interests accumulated from lending
/// @dev This function is called by a `PoolManager` contract having some yield farming strategies associated
/// @dev To prevent flash loans, the `sanRate` is not directly updated, it is updated at the blocks that follow
function accumulateInterest(uint256 gain) external override {
// Searching collateral data
Collateral storage col = collateralMap[IPoolManager(msg.sender)];
_contractMapCheck(col);
// A part of the gain goes to SLPs, the rest to the surplus of the protocol
_updateSanRate((gain * col.slpData.interestsForSLPs) / BASE_PARAMS, col);
}
/// @notice Takes into account a loss made by a yield farming strategy
/// @param loss Loss made by the yield farming strategy
/// @dev This function is called by a `PoolManager` contract having some yield farming strategies associated
/// @dev Fees are not accumulated for this function before being distributed: everything is directly used to
/// update the `sanRate`
function signalLoss(uint256 loss) external override {
// Searching collateral data
IPoolManager poolManager = IPoolManager(msg.sender);
Collateral storage col = collateralMap[poolManager];
_contractMapCheck(col);
uint256 sanMint = col.sanToken.totalSupply();
if (sanMint != 0) {
// Updating the `sanRate` and the `lockedInterests` by taking into account a loss
if (col.sanRate * sanMint + col.slpData.lockedInterests * BASE_TOKENS > loss * BASE_TOKENS) {
// The loss is first taken from the `lockedInterests`
uint256 withdrawFromLoss = col.slpData.lockedInterests;
if (withdrawFromLoss >= loss) {
withdrawFromLoss = loss;
}
col.slpData.lockedInterests -= withdrawFromLoss;
col.sanRate -= ((loss - withdrawFromLoss) * BASE_TOKENS) / sanMint;
} else {
// Normally it should be set to 0, but this would imply that no SLP can enter afterwards
// we therefore set it to 1 (equivalent to 10**(-18))
col.sanRate = 1;
col.slpData.lockedInterests = 0;
// As it is a critical time, governance pauses SLPs to solve the situation
_pause(keccak256(abi.encodePacked(SLP, address(poolManager))));
}
emit SanRateUpdated(address(col.token), col.sanRate);
}
}
// ============================== HAs ==========================================
/// @notice Transforms a HA position into a SLP Position
/// @param amount The amount to transform
/// @param user Address to mint sanTokens to
/// @dev Can only be called by a `PerpetualManager` contract
/// @dev This is typically useful when a HA wishes to cash out but there is not enough collateral
/// in reserves
function convertToSLP(uint256 amount, address user) external override {
// Data about the `PerpetualManager` calling the function is fetched using the `contractMap`
IPoolManager poolManager = _contractMap[msg.sender];
Collateral storage col = collateralMap[poolManager];
_contractMapCheck(col);
// If SLPs are paused, in this situation, then this transaction should revert
// In this extremely rare case, governance should take action and also pause HAs
_whenNotPaused(SLP, address(poolManager));
_updateSanRate(0, col);
col.sanToken.mint(user, (amount * BASE_TOKENS) / col.sanRate);
}
/// @notice Sets the proportion of `stocksUsers` available for perpetuals
/// @param _targetHAHedge New value of the hedge ratio that the protocol wants to arrive to
/// @dev Can only be called by the `PerpetualManager`
function setTargetHAHedge(uint64 _targetHAHedge) external override {
// Data about the `PerpetualManager` calling the function is fetched using the `contractMap`
IPoolManager poolManager = _contractMap[msg.sender];
Collateral storage col = collateralMap[poolManager];
_contractMapCheck(col);
col.feeData.targetHAHedge = _targetHAHedge;
// No need to issue an event here, one has already been issued by the corresponding `PerpetualManager`
}
// ============================ VIEW FUNCTIONS =================================
/// @notice Transmits to the `PerpetualManager` the max amount of collateral (in stablecoin value) HAs can hedge
/// @return _stocksUsers All stablecoins currently assigned to the pool of the caller
/// @dev This function will not return something relevant if it is not called by a `PerpetualManager`
function getStocksUsers() external view override returns (uint256 _stocksUsers) {
_stocksUsers = collateralMap[_contractMap[msg.sender]].stocksUsers;
}
/// @notice Returns the collateral ratio for this stablecoin
/// @dev The ratio returned is scaled by `BASE_PARAMS` since the value is used to
/// in the `FeeManager` contrat to be compared with the values in `xArrays` expressed in `BASE_PARAMS`
function getCollateralRatio() external view override returns (uint256) {
uint256 mints = agToken.totalSupply();
if (mints == 0) {
// If nothing has been minted, the collateral ratio is infinity
return type(uint256).max;
}
uint256 val;
for (uint256 i = 0; i < _managerList.length; i++) {
// Oracle needs to be called for each collateral to compute the collateral ratio
val += collateralMap[_managerList[i]].oracle.readQuote(_managerList[i].getTotalAsset());
}
return (val * BASE_PARAMS) / mints;
}
// ============================== KEEPERS ======================================
/// @notice Updates all the fees not depending on personal agents inputs via a keeper calling the corresponding
/// function in the `FeeManager` contract
/// @param _bonusMalusMint New corrector of user mint fees for this collateral. These fees will correct
/// the mint fees from users that just depend on the hedge curve by HAs by introducing other dependencies.
/// In normal times they will be equal to `BASE_PARAMS` meaning fees will just depend on the hedge ratio
/// @param _bonusMalusBurn New corrector of user burn fees, depending on collateral ratio
/// @param _slippage New global slippage (the SLP fees from withdrawing) factor
/// @param _slippageFee New global slippage fee (the non distributed accumulated fees) factor
function setFeeKeeper(
uint64 _bonusMalusMint,
uint64 _bonusMalusBurn,
uint64 _slippage,
uint64 _slippageFee
) external override {
// Fetching data about the `FeeManager` contract calling this function
// It is stored in the `_contractMap`
Collateral storage col = collateralMap[_contractMap[msg.sender]];
_contractMapCheck(col);
col.feeData.bonusMalusMint = _bonusMalusMint;
col.feeData.bonusMalusBurn = _bonusMalusBurn;
col.slpData.slippage = _slippage;
col.slpData.slippageFee = _slippageFee;
// An event is already emitted in the `FeeManager` contract
}
// ============================== AgToken ======================================
/// @notice Allows the `agToken` contract to update the `stocksUsers` for a given collateral after a burn
/// with no redeem
/// @param amount Amount by which `stocksUsers` should decrease
/// @param poolManager Reference to `PoolManager` for which `stocksUsers` needs to be updated
/// @dev This function can be called by the `agToken` contract after a burn of agTokens for which no collateral has been
/// redeemed
function updateStocksUsers(uint256 amount, address poolManager) external override {
require(msg.sender == address(agToken), "3");
Collateral storage col = collateralMap[IPoolManager(poolManager)];
_contractMapCheck(col);
require(col.stocksUsers >= amount, "4");
col.stocksUsers -= amount;
emit StocksUsersUpdated(address(col.token), col.stocksUsers);
}
// ================================= GOVERNANCE ================================
// =============================== Core Functions ==============================
/// @notice Changes the `Core` contract
/// @param newCore New core address
/// @dev This function can only be called by the `Core` contract
function setCore(address newCore) external override onlyRole(CORE_ROLE) {
// Access control for this contract
_revokeRole(CORE_ROLE, address(_core));
_grantRole(CORE_ROLE, newCore);
_core = ICore(newCore);
}
/// @notice Adds a new governor address
/// @param governor New governor address
/// @dev This function propagates changes from `Core` to other contracts
/// @dev Propagating changes like that allows to maintain the protocol's integrity
function addGovernor(address governor) external override onlyRole(CORE_ROLE) {
// Access control for this contract
_grantRole(GOVERNOR_ROLE, governor);
_grantRole(GUARDIAN_ROLE, governor);
for (uint256 i = 0; i < _managerList.length; i++) {
// The `PoolManager` will echo the changes across all the corresponding contracts
_managerList[i].addGovernor(governor);
}
}
/// @notice Removes a governor address which loses its role
/// @param governor Governor address to remove
/// @dev This function propagates changes from `Core` to other contracts
/// @dev Propagating changes like that allows to maintain the protocol's integrity
/// @dev It has already been checked in the `Core` that this address could be removed
/// and that it would not put the protocol in a situation with no governor at all
function removeGovernor(address governor) external override onlyRole(CORE_ROLE) {
// Access control for this contract
_revokeRole(GOVERNOR_ROLE, governor);
_revokeRole(GUARDIAN_ROLE, governor);
for (uint256 i = 0; i < _managerList.length; i++) {
// The `PoolManager` will echo the changes across all the corresponding contracts
_managerList[i].removeGovernor(governor);
}
}
/// @notice Changes the guardian address
/// @param newGuardian New guardian address
/// @param oldGuardian Old guardian address
/// @dev This function propagates changes from `Core` to other contracts
/// @dev The zero check for the guardian address has already been performed by the `Core`
/// contract
function setGuardian(address newGuardian, address oldGuardian) external override onlyRole(CORE_ROLE) {
_revokeRole(GUARDIAN_ROLE, oldGuardian);
_grantRole(GUARDIAN_ROLE, newGuardian);
for (uint256 i = 0; i < _managerList.length; i++) {
_managerList[i].setGuardian(newGuardian, oldGuardian);
}
}
/// @notice Revokes the guardian address
/// @param oldGuardian Guardian address to revoke
/// @dev This function propagates changes from `Core` to other contracts
function revokeGuardian(address oldGuardian) external override onlyRole(CORE_ROLE) {
_revokeRole(GUARDIAN_ROLE, oldGuardian);
for (uint256 i = 0; i < _managerList.length; i++) {
_managerList[i].revokeGuardian(oldGuardian);
}
}
// ============================= Governor Functions ============================
/// @notice Deploys a new collateral by creating the correct references in the corresponding contracts
/// @param poolManager Contract managing and storing this collateral for this stablecoin
/// @param perpetualManager Contract managing HA perpetuals for this stablecoin
/// @param oracle Reference to the oracle that will give the price of the collateral with respect to the stablecoin
/// @param sanToken Reference to the sanTokens associated to the collateral
/// @dev All the references in parameters should correspond to contracts that have already been deployed and
/// initialized with appropriate references
/// @dev After calling this function, governance should initialize all parameters corresponding to this new collateral
function deployCollateral(
IPoolManager poolManager,
IPerpetualManager perpetualManager,
IFeeManager feeManager,
IOracle oracle,
ISanToken sanToken
) external onlyRole(GOVERNOR_ROLE) {
// If the `sanToken`, `poolManager`, `perpetualManager` and `feeManager` were zero
// addresses, the following require would fail
// The only elements that are checked here are those that are defined in the constructors/initializers
// of the concerned contracts
require(
sanToken.stableMaster() == address(this) &&
sanToken.poolManager() == address(poolManager) &&
poolManager.stableMaster() == address(this) &&
perpetualManager.poolManager() == address(poolManager) &&
// If the `feeManager` is not initialized with the correct `poolManager` then this function
// will revert when `poolManager.deployCollateral` will be executed
feeManager.stableMaster() == address(this),
"9"
);
// Checking if the base of the tokens and of the oracle are not similar with one another
address token = poolManager.token();
uint256 collatBase = 10**(IERC20Metadata(token).decimals());
// If the address of the oracle was the zero address, the following would revert
require(oracle.inBase() == collatBase, "11");
// Checking if the collateral has not already been deployed
Collateral storage col = collateralMap[poolManager];
require(address(col.token) == address(0), "13");
// Creating the correct references
col.token = IERC20(token);
col.sanToken = sanToken;
col.perpetualManager = perpetualManager;
col.oracle = oracle;
// Initializing with the correct values
col.sanRate = BASE_TOKENS;
col.collatBase = collatBase;
// Adding the correct references in the `contractMap` we use in order not to have to pass addresses when
// calling the `StableMaster` from the `PerpetualManager` contract, or the `FeeManager` contract
// This is equivalent to granting Access Control roles for these contracts
_contractMap[address(perpetualManager)] = poolManager;
_contractMap[address(feeManager)] = poolManager;
_managerList.push(poolManager);
// Pausing agents at deployment to leave governance time to set parameters
// The `PerpetualManager` contract is automatically paused after being initialized, so HAs will not be able to
// interact with the protocol
_pause(keccak256(abi.encodePacked(SLP, address(poolManager))));
_pause(keccak256(abi.encodePacked(STABLE, address(poolManager))));
// Fetching the governor list and the guardian to initialize the `poolManager` correctly
address[] memory governorList = _core.governorList();
address guardian = _core.guardian();
// Propagating the deployment and passing references to the corresponding contracts
poolManager.deployCollateral(governorList, guardian, perpetualManager, feeManager, oracle);
emit CollateralDeployed(address(poolManager), address(perpetualManager), address(sanToken), address(oracle));
}
/// @notice Removes a collateral from the list of accepted collateral types and pauses all actions associated
/// to this collateral
/// @param poolManager Reference to the contract managing this collateral for this stablecoin in the protocol
/// @param settlementContract Settlement contract that will be used to close everyone's positions and to let
/// users, SLPs and HAs redeem if not all a portion of their claim
/// @dev Since this function has the ability to transfer the contract's funds to another contract, it should
/// only be accessible to the governor
/// @dev Before calling this function, governance should make sure that all the collateral lent to strategies
/// has been withdrawn
function revokeCollateral(IPoolManager poolManager, ICollateralSettler settlementContract)
external
onlyRole(GOVERNOR_ROLE)
{
// Checking if the `poolManager` given here is well in the list of managers and taking advantage of that to remove
// the `poolManager` from the list
uint256 indexMet;
uint256 managerListLength = _managerList.length;
require(managerListLength >= 1, "10");
for (uint256 i = 0; i < managerListLength - 1; i++) {
if (_managerList[i] == poolManager) {
indexMet = 1;
_managerList[i] = _managerList[managerListLength - 1];
break;
}
}
require(indexMet == 1 || _managerList[managerListLength - 1] == poolManager, "10");
_managerList.pop();
Collateral memory col = collateralMap[poolManager];
// Deleting the references of the associated contracts: `perpetualManager` and `keeper` in the
// `_contractMap` and `poolManager` from the `collateralMap`
delete _contractMap[poolManager.feeManager()];
delete _contractMap[address(col.perpetualManager)];
delete collateralMap[poolManager];
emit CollateralRevoked(address(poolManager));
// Pausing entry (and exits for HAs)
col.perpetualManager.pause();
// No need to pause `SLP` and `STABLE_HOLDERS` as deleting the entry associated to the `poolManager`
// in the `collateralMap` will make everything revert
// Transferring the whole balance to global settlement
uint256 balance = col.token.balanceOf(address(poolManager));
col.token.safeTransferFrom(address(poolManager), address(settlementContract), balance);
// Settlement works with a fixed oracle value for HAs, it needs to be computed here
uint256 oracleValue = col.oracle.readLower();
// Notifying the global settlement contract with the properties of the contract to settle
// In case of global shutdown, there would be one settlement contract per collateral type
// Not using the `lockedInterests` to update the value of the sanRate
settlementContract.triggerSettlement(oracleValue, col.sanRate, col.stocksUsers);
}
// ============================= Guardian Functions ============================
/// @notice Pauses an agent's actions within this contract for a given collateral type for this stablecoin
/// @param agent Bytes representing the agent (`SLP` or `STABLE`) and the collateral type that is going to
/// be paused. To get the `bytes32` from a string, we use in Solidity a `keccak256` function
/// @param poolManager Reference to the contract managing this collateral for this stablecoin in the protocol and
/// for which `agent` needs to be paused
/// @dev If agent is `STABLE`, it is going to be impossible for users to mint stablecoins using collateral or to burn
/// their stablecoins
/// @dev If agent is `SLP`, it is going to be impossible for SLPs to deposit collateral and receive
/// sanTokens in exchange, or to withdraw collateral from their sanTokens
function pause(bytes32 agent, IPoolManager poolManager) external override onlyRole(GUARDIAN_ROLE) {
Collateral storage col = collateralMap[poolManager];
// Checking for the `poolManager`
_contractMapCheck(col);
_pause(keccak256(abi.encodePacked(agent, address(poolManager))));
}
/// @notice Unpauses an agent's action for a given collateral type for this stablecoin
/// @param agent Agent (`SLP` or `STABLE`) to unpause the action of
/// @param poolManager Reference to the associated `PoolManager`
/// @dev Before calling this function, the agent should have been paused for this collateral
function unpause(bytes32 agent, IPoolManager poolManager) external override onlyRole(GUARDIAN_ROLE) {
Collateral storage col = collateralMap[poolManager];
// Checking for the `poolManager`
_contractMapCheck(col);
_unpause(keccak256(abi.encodePacked(agent, address(poolManager))));
}
/// @notice Updates the `stocksUsers` for a given pair of collateral
/// @param amount Amount of `stocksUsers` to transfer from a pool to another
/// @param poolManagerUp Reference to `PoolManager` for which `stocksUsers` needs to increase
/// @param poolManagerDown Reference to `PoolManager` for which `stocksUsers` needs to decrease
/// @dev This function can be called in case where the reserves of the protocol for each collateral do not exactly
/// match what is stored in the `stocksUsers` because of increases or decreases in collateral prices at times
/// in which the protocol was not fully hedged by HAs
/// @dev With this function, governance can allow/prevent more HAs coming in a pool while preventing/allowing HAs
/// from other pools because the accounting variable of `stocksUsers` does not really match
function rebalanceStocksUsers(
uint256 amount,
IPoolManager poolManagerUp,
IPoolManager poolManagerDown
) external onlyRole(GUARDIAN_ROLE) {
Collateral storage colUp = collateralMap[poolManagerUp];
Collateral storage colDown = collateralMap[poolManagerDown];
// Checking for the `poolManager`
_contractMapCheck(colUp);
_contractMapCheck(colDown);
// The invariant `col.stocksUsers <= col.capOnStableMinted` should remain true even after a
// governance update
require(colUp.stocksUsers + amount <= colUp.feeData.capOnStableMinted, "8");
colDown.stocksUsers -= amount;
colUp.stocksUsers += amount;
emit StocksUsersUpdated(address(colUp.token), colUp.stocksUsers);
emit StocksUsersUpdated(address(colDown.token), colDown.stocksUsers);
}
/// @notice Propagates the change of oracle for one collateral to all the contracts which need to have
/// the correct oracle reference
/// @param _oracle New oracle contract for the pair collateral/stablecoin
/// @param poolManager Reference to the `PoolManager` contract associated to the collateral
function setOracle(IOracle _oracle, IPoolManager poolManager)
external
onlyRole(GOVERNOR_ROLE)
zeroCheck(address(_oracle))
{
Collateral storage col = collateralMap[poolManager];
// Checking for the `poolManager`
_contractMapCheck(col);
require(col.oracle != _oracle, "12");
// The `inBase` of the new oracle should be the same as the `_collatBase` stored for this collateral
require(col.collatBase == _oracle.inBase(), "11");
col.oracle = _oracle;
emit OracleUpdated(address(poolManager), address(_oracle));
col.perpetualManager.setOracle(_oracle);
}
/// @notice Changes the parameters to cap the number of stablecoins you can issue using one
/// collateral type and the maximum interests you can distribute to SLPs in a sanRate update
/// in a block
/// @param _capOnStableMinted New value of the cap
/// @param _maxInterestsDistributed Maximum amount of interests distributed to SLPs in a block
/// @param poolManager Reference to the `PoolManager` contract associated to the collateral
function setCapOnStableAndMaxInterests(
uint256 _capOnStableMinted,
uint256 _maxInterestsDistributed,
IPoolManager poolManager
) external override onlyRole(GUARDIAN_ROLE) {
Collateral storage col = collateralMap[poolManager];
// Checking for the `poolManager`
_contractMapCheck(col);
// The invariant `col.stocksUsers <= col.capOnStableMinted` should remain true even after a
// governance update
require(_capOnStableMinted >= col.stocksUsers, "8");
col.feeData.capOnStableMinted = _capOnStableMinted;
col.slpData.maxInterestsDistributed = _maxInterestsDistributed;
emit CapOnStableAndMaxInterestsUpdated(address(poolManager), _capOnStableMinted, _maxInterestsDistributed);
}
/// @notice Sets a new `FeeManager` contract and removes the old one which becomes useless
/// @param newFeeManager New `FeeManager` contract
/// @param oldFeeManager Old `FeeManager` contract
/// @param poolManager Reference to the contract managing this collateral for this stablecoin in the protocol
/// and associated to the `FeeManager` to update
function setFeeManager(
address newFeeManager,
address oldFeeManager,
IPoolManager poolManager
) external onlyRole(GUARDIAN_ROLE) zeroCheck(newFeeManager) {
Collateral storage col = collateralMap[poolManager];
// Checking for the `poolManager`
_contractMapCheck(col);
require(_contractMap[oldFeeManager] == poolManager, "10");
require(newFeeManager != oldFeeManager, "14");
delete _contractMap[oldFeeManager];
_contractMap[newFeeManager] = poolManager;
emit FeeManagerUpdated(address(poolManager), newFeeManager);
poolManager.setFeeManager(IFeeManager(newFeeManager));
}
/// @notice Sets the proportion of fees from burn/mint of users and the proportion
/// of lending interests going to SLPs
/// @param _feesForSLPs New proportion of mint/burn fees going to SLPs
/// @param _interestsForSLPs New proportion of interests from lending going to SLPs
/// @dev The higher these proportions the bigger the APY for SLPs
/// @dev These proportions should be inferior to `BASE_PARAMS`
function setIncentivesForSLPs(
uint64 _feesForSLPs,
uint64 _interestsForSLPs,
IPoolManager poolManager
) external override onlyRole(GUARDIAN_ROLE) onlyCompatibleFees(_feesForSLPs) onlyCompatibleFees(_interestsForSLPs) {
Collateral storage col = collateralMap[poolManager];
_contractMapCheck(col);
col.slpData.feesForSLPs = _feesForSLPs;
col.slpData.interestsForSLPs = _interestsForSLPs;
emit SLPsIncentivesUpdated(address(poolManager), _feesForSLPs, _interestsForSLPs);
}
/// @notice Sets the x array (ie ratios between amount hedged by HAs and amount to hedge)
/// and the y array (ie values of fees at thresholds) used to compute mint and burn fees for users
/// @param poolManager Reference to the `PoolManager` handling the collateral
/// @param _xFee Thresholds of hedge ratios
/// @param _yFee Values of the fees at thresholds
/// @param _mint Whether mint fees or burn fees should be updated
/// @dev The evolution of the fees between two thresholds is linear
/// @dev The length of the two arrays should be the same
/// @dev The values of `_xFee` should be in ascending order
/// @dev For mint fees, values in the y-array below should normally be decreasing: the higher the `x` the cheaper
/// it should be for stable seekers to come in as a high `x` corresponds to a high demand for volatility and hence
/// to a situation where all the collateral can be hedged
/// @dev For burn fees, values in the array below should normally be decreasing: the lower the `x` the cheaper it should
/// be for stable seekers to go out, as a low `x` corresponds to low demand for volatility and hence
/// to a situation where the protocol has a hard time covering its collateral
function setUserFees(
IPoolManager poolManager,
uint64[] memory _xFee,
uint64[] memory _yFee,
uint8 _mint
) external override onlyRole(GUARDIAN_ROLE) onlyCompatibleInputArrays(_xFee, _yFee) {
Collateral storage col = collateralMap[poolManager];
_contractMapCheck(col);
if (_mint > 0) {
col.feeData.xFeeMint = _xFee;
col.feeData.yFeeMint = _yFee;
} else {
col.feeData.xFeeBurn = _xFee;
col.feeData.yFeeBurn = _yFee;
}
emit FeeArrayUpdated(address(poolManager), _xFee, _yFee, _mint);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../external/AccessControlUpgradeable.sol";
import "../interfaces/IAgToken.sol";
import "../interfaces/ICollateralSettler.sol";
import "../interfaces/ICore.sol";
import "../interfaces/IFeeManager.sol";
import "../interfaces/IOracle.sol";
import "../interfaces/IPerpetualManager.sol";
import "../interfaces/IPoolManager.sol";
import "../interfaces/ISanToken.sol";
import "../interfaces/IStableMaster.sol";
import "../utils/FunctionUtils.sol";
import "../utils/PausableMapUpgradeable.sol";
/// @title StableMasterEvents
/// @author Angle Core Team
/// @notice `StableMaster` is the contract handling all the collateral types accepted for a given stablecoin
/// It does all the accounting and is the point of entry in the protocol for stable holders and seekers as well as SLPs
/// @dev This file contains all the events of the `StableMaster` contract
contract StableMasterEvents {
event SanRateUpdated(address indexed _token, uint256 _newSanRate);
event StocksUsersUpdated(address indexed _poolManager, uint256 _stocksUsers);
event MintedStablecoins(address indexed _poolManager, uint256 amount, uint256 amountForUserInStable);
event BurntStablecoins(address indexed _poolManager, uint256 amount, uint256 redeemInC);
// ============================= Governors =====================================
event CollateralDeployed(
address indexed _poolManager,
address indexed _perpetualManager,
address indexed _sanToken,
address _oracle
);
event CollateralRevoked(address indexed _poolManager);
// ========================= Parameters update =================================
event OracleUpdated(address indexed _poolManager, address indexed _oracle);
event FeeManagerUpdated(address indexed _poolManager, address indexed newFeeManager);
event CapOnStableAndMaxInterestsUpdated(
address indexed _poolManager,
uint256 _capOnStableMinted,
uint256 _maxInterestsDistributed
);
event SLPsIncentivesUpdated(address indexed _poolManager, uint64 _feesForSLPs, uint64 _interestsForSLPs);
event FeeArrayUpdated(address indexed _poolManager, uint64[] _xFee, uint64[] _yFee, uint8 _type);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "./StableMaster.sol";
/// @title StableMasterFront
/// @author Angle Core Team
/// @notice `StableMaster` is the contract handling all the collateral types accepted for a given stablecoin
/// It does all the accounting and is the point of entry in the protocol for stable holders and seekers as well as SLPs
/// @dev This file contains the front end, that is all external functions associated to the given stablecoin
contract StableMasterFront is StableMaster {
using SafeERC20 for IERC20;
// ============================ CONSTRUCTORS AND DEPLOYERS =====================
/// @notice Initializes the `StableMaster` contract
/// @param core_ Address of the `Core` contract handling all the different `StableMaster` contracts
function initialize(address core_) external zeroCheck(core_) initializer {
__AccessControl_init();
// Access control
_core = ICore(core_);
_setupRole(CORE_ROLE, core_);
// `Core` is admin of all roles
_setRoleAdmin(CORE_ROLE, CORE_ROLE);
_setRoleAdmin(GOVERNOR_ROLE, CORE_ROLE);
_setRoleAdmin(GUARDIAN_ROLE, CORE_ROLE);
// All the roles that are specific to a given collateral can be changed by the governor
// in the `deployCollateral`, `revokeCollateral` and `setFeeManager` functions by updating the `contractMap`
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
// ============================= USERS =========================================
/// @notice Lets a user send collateral to the system to mint stablecoins
/// @param amount Amount of collateral sent
/// @param user Address of the contract or the person to give the minted tokens to
/// @param poolManager Address of the `PoolManager` of the required collateral
/// @param minStableAmount Minimum amount of stablecoins the user wants to get with this transaction
/// @dev This function works as a swap from a user perspective from collateral to stablecoins
/// @dev It is impossible to mint tokens and to have them sent to the zero address: there
/// would be an issue with the `_mint` function called by the `AgToken` contract
/// @dev The parameter `minStableAmount` serves as a slippage protection for users
/// @dev From a user perspective, this function is equivalent to a swap between collateral and
/// stablecoins
function mint(
uint256 amount,
address user,
IPoolManager poolManager,
uint256 minStableAmount
) external {
Collateral storage col = collateralMap[poolManager];
_contractMapCheck(col);
// Checking if the contract is paused for this agent
_whenNotPaused(STABLE, address(poolManager));
// No overflow check are needed for the amount since it's never casted to `int` and Solidity 0.8.0
// automatically handles overflows
col.token.safeTransferFrom(msg.sender, address(poolManager), amount);
// Getting a quote for the amount of stablecoins to issue
// We read the lowest oracle value we get for this collateral/stablecoin pair: it's the one
// that is most at the advantage of the protocol
// Decimals are handled directly in the oracle contract
uint256 amountForUserInStable = col.oracle.readQuoteLower(amount);
// Getting the fees paid for this transaction, expressed in `BASE_PARAMS`
// Floor values are taken for fees computation, as what is earned by users is lost by SLP
// when calling `_updateSanRate` and vice versa
uint256 fees = _computeFeeMint(amountForUserInStable, col);
// Computing the net amount that will be taken into account for this user by deducing fees
amountForUserInStable = (amountForUserInStable * (BASE_PARAMS - fees)) / BASE_PARAMS;
// Checking if the user got more stablecoins than the least amount specified in the parameters of the
// function
require(amountForUserInStable >= minStableAmount, "15");
// Updating the `stocksUsers` for this collateral, that is the amount of collateral that was
// brought by users
col.stocksUsers += amountForUserInStable;
// Checking if stablecoins can still be issued using this collateral type
require(col.stocksUsers <= col.feeData.capOnStableMinted, "16");
// Event needed to track `col.stocksUsers` off-chain
emit MintedStablecoins(address(poolManager), amount, amountForUserInStable);
// Distributing the fees taken to SLPs
// The `fees` variable computed above is a proportion expressed in `BASE_PARAMS`.
// To compute the amount of fees in collateral value, we can directly use the `amount` of collateral
// entered by the user
// Not all the fees are distributed to SLPs, a portion determined by `col.slpData.feesForSLPs` goes to surplus
_updateSanRate((amount * fees * col.slpData.feesForSLPs) / (BASE_PARAMS**2), col);
// Minting
agToken.mint(user, amountForUserInStable);
}
/// @notice Lets a user burn agTokens (stablecoins) and receive the collateral specified by the `poolManager`
/// in exchange
/// @param amount Amount of stable asset burnt
/// @param burner Address from which the agTokens will be burnt
/// @param dest Address where collateral is going to be
/// @param poolManager Collateral type requested by the user burning
/// @param minCollatAmount Minimum amount of collateral that the user is willing to get for this transaction
/// @dev The `msg.sender` should have approval to burn from the `burner` or the `msg.sender` should be the `burner`
/// @dev If there are not enough reserves this transaction will revert and the user will have to come back to the
/// protocol with a correct amount. Checking for the reserves currently available in the `PoolManager`
/// is something that should be handled by the front interacting with this contract
/// @dev In case there are not enough reserves, strategies should be harvested or their debt ratios should be adjusted
/// by governance to make sure that users, HAs or SLPs withdrawing always have free collateral they can use
/// @dev From a user perspective, this function is equivalent to a swap from stablecoins to collateral
function burn(
uint256 amount,
address burner,
address dest,
IPoolManager poolManager,
uint256 minCollatAmount
) external {
// Searching collateral data
Collateral storage col = collateralMap[poolManager];
// Checking the collateral requested
_contractMapCheck(col);
_whenNotPaused(STABLE, address(poolManager));
// Checking if the amount is not going to make the `stocksUsers` negative
// A situation like that is likely to happen if users mint using one collateral type and in volume redeem
// another collateral type
// In this situation, governance should rapidly react to pause the pool and then rebalance the `stocksUsers`
// between different collateral types, or at least rebalance what is stored in the reserves through
// the `recoverERC20` function followed by a swap and then a transfer
require(amount <= col.stocksUsers, "17");
// Burning the tokens will revert if there are not enough tokens in balance or if the `msg.sender`
// does not have approval from the burner
// A reentrancy attack is potentially possible here as state variables are written after the burn,
// but as the `AgToken` is a protocol deployed contract, it can be trusted. Still, `AgToken` is
// upgradeable by governance, the following could become risky in case of a governance attack
if (burner == msg.sender) {
agToken.burnSelf(amount, burner);
} else {
agToken.burnFrom(amount, burner, msg.sender);
}
// Getting the highest possible oracle value
uint256 oracleValue = col.oracle.readUpper();
// Converting amount of agTokens in collateral and computing how much should be reimbursed to the user
// Amount is in `BASE_TOKENS` and the outputted collateral amount should be in collateral base
uint256 amountInC = (amount * col.collatBase) / oracleValue;
// Computing how much of collateral can be redeemed by the user after taking fees
// The value of the fees here is `_computeFeeBurn(amount,col)` (it is a proportion expressed in `BASE_PARAMS`)
// The real value of what can be redeemed by the user is `amountInC * (BASE_PARAMS - fees) / BASE_PARAMS`,
// but we prefer to avoid doing multiplications after divisions
uint256 redeemInC = (amount * (BASE_PARAMS - _computeFeeBurn(amount, col)) * col.collatBase) /
(oracleValue * BASE_PARAMS);
require(redeemInC >= minCollatAmount, "15");
// Updating the `stocksUsers` that is the amount of collateral that was brought by users
col.stocksUsers -= amount;
// Event needed to track `col.stocksUsers` off-chain
emit BurntStablecoins(address(poolManager), amount, redeemInC);
// Computing the exact amount of fees from this transaction and accumulating it for SLPs
_updateSanRate(((amountInC - redeemInC) * col.slpData.feesForSLPs) / BASE_PARAMS, col);
col.token.safeTransferFrom(address(poolManager), dest, redeemInC);
}
// ============================== SLPs =========================================
/// @notice Lets a SLP enter the protocol by sending collateral to the system in exchange of sanTokens
/// @param user Address of the SLP to send sanTokens to
/// @param amount Amount of collateral sent
/// @param poolManager Address of the `PoolManager` of the required collateral
function deposit(
uint256 amount,
address user,
IPoolManager poolManager
) external {
// Searching collateral data
Collateral storage col = collateralMap[poolManager];
_contractMapCheck(col);
_whenNotPaused(SLP, address(poolManager));
_updateSanRate(0, col);
// No overflow check needed for the amount since it's never casted to int and Solidity versions above 0.8.0
// automatically handle overflows
col.token.safeTransferFrom(msg.sender, address(poolManager), amount);
col.sanToken.mint(user, (amount * BASE_TOKENS) / col.sanRate);
}
/// @notice Lets a SLP burn of sanTokens and receive the corresponding collateral back in exchange at the
/// current exchange rate between sanTokens and collateral
/// @param amount Amount of sanTokens burnt by the SLP
/// @param burner Address that will burn its sanTokens
/// @param dest Address that will receive the collateral
/// @param poolManager Address of the `PoolManager` of the required collateral
/// @dev The `msg.sender` should have approval to burn from the `burner` or the `msg.sender` should be the `burner`
/// @dev This transaction will fail if the `PoolManager` does not have enough reserves, the front will however be here
/// to notify them that they cannot withdraw
/// @dev In case there are not enough reserves, strategies should be harvested or their debt ratios should be adjusted
/// by governance to make sure that users, HAs or SLPs withdrawing always have free collateral they can use
function withdraw(
uint256 amount,
address burner,
address dest,
IPoolManager poolManager
) external {
Collateral storage col = collateralMap[poolManager];
_contractMapCheck(col);
_whenNotPaused(SLP, address(poolManager));
_updateSanRate(0, col);
if (burner == msg.sender) {
col.sanToken.burnSelf(amount, burner);
} else {
col.sanToken.burnFrom(amount, burner, msg.sender);
}
// Computing the amount of collateral to give back to the SLP depending on slippage and on the `sanRate`
uint256 redeemInC = (amount * (BASE_PARAMS - col.slpData.slippage) * col.sanRate) / (BASE_TOKENS * BASE_PARAMS);
col.token.safeTransferFrom(address(poolManager), dest, redeemInC);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "./StableMasterStorage.sol";
/// @title StableMasterInternal
/// @author Angle Core Team
/// @notice `StableMaster` is the contract handling all the collateral types accepted for a given stablecoin
/// It does all the accounting and is the point of entry in the protocol for stable holders and seekers as well as SLPs
/// @dev This file contains all the internal function of the `StableMaster` contract
contract StableMasterInternal is StableMasterStorage, PausableMapUpgradeable {
/// @notice Checks if the `msg.sender` calling the contract has the right to do it
/// @param col Struct for the collateral associated to the caller address
/// @dev Since the `StableMaster` contract uses a `contractMap` that stores addresses of some verified
/// protocol's contracts in it, and since the roles corresponding to these addresses are never admin roles
/// it is cheaper not to use for these contracts OpenZeppelin's access control logic
/// @dev A non null associated token address is what is used to check if a `PoolManager` has well been initialized
/// @dev We could set `PERPETUALMANAGER_ROLE`, `POOLMANAGER_ROLE` and `FEEMANAGER_ROLE` for this
/// contract, but this would actually be inefficient
function _contractMapCheck(Collateral storage col) internal view {
require(address(col.token) != address(0), "3");
}
/// @notice Checks if the protocol has been paused for an agent and for a given collateral type for this
/// stablecoin
/// @param agent Name of the agent to check, it is either going to be `STABLE` or `SLP`
/// @param poolManager `PoolManager` contract for which to check pauses
function _whenNotPaused(bytes32 agent, address poolManager) internal view {
require(!paused[keccak256(abi.encodePacked(agent, poolManager))], "18");
}
/// @notice Updates the `sanRate` that is the exchange rate between sanTokens given to SLPs and collateral or
/// accumulates fees to be distributed to SLPs before doing it at next block
/// @param toShare Amount of interests that needs to be redistributed to the SLPs through the `sanRate`
/// @param col Struct for the collateral of interest here which values are going to be updated
/// @dev This function can only increase the `sanRate` and is not used to take into account a loss made through
/// lending or another yield farming strategy: this is done in the `signalLoss` function
/// @dev The `sanRate` is only be updated from the fees accumulated from previous blocks and the fees to share to SLPs
/// are just accumulated to be distributed at next block
/// @dev A flashloan attack could consist in seeing fees to be distributed, deposit, increase the `sanRate` and then
/// withdraw: what is done with the `lockedInterests` parameter is a way to mitigate that
/// @dev Another solution against flash loans would be to have a non null `slippage` at all times: this is far from ideal
/// for SLPs in the first place
function _updateSanRate(uint256 toShare, Collateral storage col) internal {
uint256 _lockedInterests = col.slpData.lockedInterests;
// Checking if the `sanRate` has been updated in the current block using past block fees
// This is a way to prevent flash loans attacks when an important amount of fees are going to be distributed
// in a block: fees are stored but will just be distributed to SLPs who will be here during next blocks
if (block.timestamp != col.slpData.lastBlockUpdated && _lockedInterests > 0) {
uint256 sanMint = col.sanToken.totalSupply();
if (sanMint != 0) {
// Checking if the update is too important and should be made in multiple blocks
if (_lockedInterests > col.slpData.maxInterestsDistributed) {
// `sanRate` is expressed in `BASE_TOKENS`
col.sanRate += (col.slpData.maxInterestsDistributed * BASE_TOKENS) / sanMint;
_lockedInterests -= col.slpData.maxInterestsDistributed;
} else {
col.sanRate += (_lockedInterests * BASE_TOKENS) / sanMint;
_lockedInterests = 0;
}
emit SanRateUpdated(address(col.token), col.sanRate);
} else {
_lockedInterests = 0;
}
}
// Adding the fees to be distributed at next block
if (toShare != 0) {
if ((col.slpData.slippageFee == 0) && (col.slpData.feesAside != 0)) {
// If the collateral ratio is big enough, all the fees or gains will be used to update the `sanRate`
// If there were fees or lending gains that had been put aside, they will be added in this case to the
// update of the `sanRate`
toShare += col.slpData.feesAside;
col.slpData.feesAside = 0;
} else if (col.slpData.slippageFee != 0) {
// Computing the fraction of fees and gains that should be left aside if the collateral ratio is too small
uint256 aside = (toShare * col.slpData.slippageFee) / BASE_PARAMS;
toShare -= aside;
// The amount of fees left aside should be rounded above
col.slpData.feesAside += aside;
}
// Updating the amount of fees to be distributed next block
_lockedInterests += toShare;
}
col.slpData.lockedInterests = _lockedInterests;
col.slpData.lastBlockUpdated = block.timestamp;
}
/// @notice Computes the current fees to be taken when minting using `amount` of collateral
/// @param amount Amount of collateral in the transaction to get stablecoins
/// @param col Struct for the collateral of interest
/// @return feeMint Mint Fees taken to users expressed in collateral
/// @dev Fees depend on the hedge ratio that is the ratio between what is hedged by HAs and what should be hedged
/// @dev The more is hedged by HAs, the smaller fees are expected to be
/// @dev Fees are also corrected by the `bonusMalusMint` parameter which induces a dependence in collateral ratio
function _computeFeeMint(uint256 amount, Collateral storage col) internal view returns (uint256 feeMint) {
uint64 feeMint64;
if (col.feeData.xFeeMint.length == 1) {
// This is done to avoid an external call in the case where the fees are constant regardless of the collateral
// ratio
feeMint64 = col.feeData.yFeeMint[0];
} else {
uint64 hedgeRatio = _computeHedgeRatio(amount + col.stocksUsers, col);
// Computing the fees based on the spread
feeMint64 = _piecewiseLinear(hedgeRatio, col.feeData.xFeeMint, col.feeData.yFeeMint);
}
// Fees could in some occasions depend on other factors like collateral ratio
// Keepers are the ones updating this part of the fees
feeMint = (feeMint64 * col.feeData.bonusMalusMint) / BASE_PARAMS;
}
/// @notice Computes the current fees to be taken when burning stablecoins
/// @param amount Amount of collateral corresponding to the stablecoins burnt in the transaction
/// @param col Struct for the collateral of interest
/// @return feeBurn Burn fees taken to users expressed in collateral
/// @dev The amount is obtained after the amount of agTokens sent is converted in collateral
/// @dev Fees depend on the hedge ratio that is the ratio between what is hedged by HAs and what should be hedged
/// @dev The more is hedged by HAs, the higher fees are expected to be
/// @dev Fees are also corrected by the `bonusMalusBurn` parameter which induces a dependence in collateral ratio
function _computeFeeBurn(uint256 amount, Collateral storage col) internal view returns (uint256 feeBurn) {
uint64 feeBurn64;
if (col.feeData.xFeeBurn.length == 1) {
// Avoiding an external call if fees are constant
feeBurn64 = col.feeData.yFeeBurn[0];
} else {
uint64 hedgeRatio = _computeHedgeRatio(col.stocksUsers - amount, col);
// Computing the fees based on the spread
feeBurn64 = _piecewiseLinear(hedgeRatio, col.feeData.xFeeBurn, col.feeData.yFeeBurn);
}
// Fees could in some occasions depend on other factors like collateral ratio
// Keepers are the ones updating this part of the fees
feeBurn = (feeBurn64 * col.feeData.bonusMalusBurn) / BASE_PARAMS;
}
/// @notice Computes the hedge ratio that is the ratio between the amount of collateral hedged by HAs
/// divided by the amount that should be hedged
/// @param newStocksUsers Value of the collateral from users to hedge
/// @param col Struct for the collateral of interest
/// @return ratio Ratio between what's hedged divided what's to hedge
/// @dev This function is typically called to compute mint or burn fees
/// @dev It seeks from the `PerpetualManager` contract associated to the collateral the total amount
/// already hedged by HAs and compares it to the amount to hedge
function _computeHedgeRatio(uint256 newStocksUsers, Collateral storage col) internal view returns (uint64 ratio) {
// Fetching the amount hedged by HAs from the corresponding `perpetualManager` contract
uint256 totalHedgeAmount = col.perpetualManager.totalHedgeAmount();
newStocksUsers = (col.feeData.targetHAHedge * newStocksUsers) / BASE_PARAMS;
if (newStocksUsers > totalHedgeAmount) ratio = uint64((totalHedgeAmount * BASE_PARAMS) / newStocksUsers);
else ratio = uint64(BASE_PARAMS);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "./StableMasterEvents.sol";
/// @title StableMasterStorage
/// @author Angle Core Team
/// @notice `StableMaster` is the contract handling all the collateral types accepted for a given stablecoin
/// It does all the accounting and is the point of entry in the protocol for stable holders and seekers as well as SLPs
/// @dev This file contains all the variables and parameters used in the `StableMaster` contract
contract StableMasterStorage is StableMasterEvents, FunctionUtils {
// All the details about a collateral that are going to be stored in `StableMaster`
struct Collateral {
// Interface for the token accepted by the underlying `PoolManager` contract
IERC20 token;
// Reference to the `SanToken` for the pool
ISanToken sanToken;
// Reference to the `PerpetualManager` for the pool
IPerpetualManager perpetualManager;
// Adress of the oracle for the change rate between
// collateral and the corresponding stablecoin
IOracle oracle;
// Amount of collateral in the reserves that comes from users
// converted in stablecoin value. Updated at minting and burning.
// A `stocksUsers` of 10 for a collateral type means that overall the balance of the collateral from users
// that minted/burnt stablecoins using this collateral is worth 10 of stablecoins
uint256 stocksUsers;
// Exchange rate between sanToken and collateral
uint256 sanRate;
// Base used in the collateral implementation (ERC20 decimal)
uint256 collatBase;
// Parameters for SLPs and update of the `sanRate`
SLPData slpData;
// All the fees parameters
MintBurnData feeData;
}
// ============================ Variables and References =====================================
/// @notice Maps a `PoolManager` contract handling a collateral for this stablecoin to the properties of the struct above
mapping(IPoolManager => Collateral) public collateralMap;
/// @notice Reference to the `AgToken` used in this `StableMaster`
/// This reference cannot be changed
IAgToken public agToken;
// Maps a contract to an address corresponding to the `IPoolManager` address
// It is typically used to avoid passing in parameters the address of the `PerpetualManager` when `PerpetualManager`
// is calling `StableMaster` to get information
// It is the Access Control equivalent for the `SanToken`, `PoolManager`, `PerpetualManager` and `FeeManager`
// contracts associated to this `StableMaster`
mapping(address => IPoolManager) internal _contractMap;
// List of all collateral managers
IPoolManager[] internal _managerList;
// Reference to the `Core` contract of the protocol
ICore internal _core;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
/// @title FunctionUtils
/// @author Angle Core Team
/// @notice Contains all the utility functions that are needed in different places of the protocol
/// @dev Functions in this contract should typically be pure functions
/// @dev This contract is voluntarily a contract and not a library to save some gas cost every time it is used
contract FunctionUtils {
/// @notice Base that is used to compute ratios and floating numbers
uint256 public constant BASE_TOKENS = 10**18;
/// @notice Base that is used to define parameters that need to have a floating value (for instance parameters
/// that are defined as ratios)
uint256 public constant BASE_PARAMS = 10**9;
/// @notice Computes the value of a linear by part function at a given point
/// @param x Point of the function we want to compute
/// @param xArray List of breaking points (in ascending order) that define the linear by part function
/// @param yArray List of values at breaking points (not necessarily in ascending order)
/// @dev The evolution of the linear by part function between two breaking points is linear
/// @dev Before the first breaking point and after the last one, the function is constant with a value
/// equal to the first or last value of the yArray
/// @dev This function is relevant if `x` is between O and `BASE_PARAMS`. If `x` is greater than that, then
/// everything will be as if `x` is equal to the greater element of the `xArray`
function _piecewiseLinear(
uint64 x,
uint64[] memory xArray,
uint64[] memory yArray
) internal pure returns (uint64) {
if (x >= xArray[xArray.length - 1]) {
return yArray[xArray.length - 1];
} else if (x <= xArray[0]) {
return yArray[0];
} else {
uint256 lower;
uint256 upper = xArray.length - 1;
uint256 mid;
while (upper - lower > 1) {
mid = lower + (upper - lower) / 2;
if (xArray[mid] <= x) {
lower = mid;
} else {
upper = mid;
}
}
if (yArray[upper] > yArray[lower]) {
// There is no risk of overflow here as in the product of the difference of `y`
// with the difference of `x`, the product is inferior to `BASE_PARAMS**2` which does not
// overflow for `uint64`
return
yArray[lower] +
((yArray[upper] - yArray[lower]) * (x - xArray[lower])) /
(xArray[upper] - xArray[lower]);
} else {
return
yArray[lower] -
((yArray[lower] - yArray[upper]) * (x - xArray[lower])) /
(xArray[upper] - xArray[lower]);
}
}
}
/// @notice Checks if the input arrays given by governance to update the fee structure is valid
/// @param xArray List of breaking points (in ascending order) that define the linear by part function
/// @param yArray List of values at breaking points (not necessarily in ascending order)
/// @dev This function is a way to avoid some governance attacks or errors
/// @dev The modifier checks if the arrays have a non null length, if their length is the same, if the values
/// in the `xArray` are in ascending order and if the values in the `xArray` and in the `yArray` are not superior
/// to `BASE_PARAMS`
modifier onlyCompatibleInputArrays(uint64[] memory xArray, uint64[] memory yArray) {
require(xArray.length == yArray.length && xArray.length > 0, "5");
for (uint256 i = 0; i <= yArray.length - 1; i++) {
require(yArray[i] <= uint64(BASE_PARAMS) && xArray[i] <= uint64(BASE_PARAMS), "6");
if (i > 0) {
require(xArray[i] > xArray[i - 1], "7");
}
}
_;
}
/// @notice Checks if the new value given for the parameter is consistent (it should be inferior to 1
/// if it corresponds to a ratio)
/// @param fees Value of the new parameter to check
modifier onlyCompatibleFees(uint64 fees) {
require(fees <= BASE_PARAMS, "4");
_;
}
/// @notice Checks if the new address given is not null
/// @param newAddress Address to check
/// @dev Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#missing-zero-address-validation
modifier zeroCheck(address newAddress) {
require(newAddress != address(0), "0");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
/// @title PausableMap
/// @author Angle Core Team after a fork from OpenZeppelin's similar Pausable Contracts
/// @notice Contract module which allows children to implement an emergency stop
/// mechanism that can be triggered by an authorized account.
/// @notice It generalizes Pausable from OpenZeppelin by allowing to specify a bytes32 that
/// should be stopped
/// @dev This module is used through inheritance
/// @dev In Angle's protocol, this contract is mainly used in `StableMasterFront`
/// to prevent SLPs and new stable holders from coming in
/// @dev The modifiers `whenNotPaused` and `whenPaused` from the original OpenZeppelin contracts were removed
/// to save some space and because they are not used in the `StableMaster` contract where this contract
/// is imported
contract PausableMapUpgradeable {
/// @dev Emitted when the pause is triggered for `name`
event Paused(bytes32 name);
/// @dev Emitted when the pause is lifted for `name`
event Unpaused(bytes32 name);
/// @dev Mapping between a name and a boolean representing the paused state
mapping(bytes32 => bool) public paused;
/// @notice Triggers stopped state for `name`
/// @param name Name for which to pause the contract
/// @dev The contract must not be paused for `name`
function _pause(bytes32 name) internal {
require(!paused[name], "18");
paused[name] = true;
emit Paused(name);
}
/// @notice Returns to normal state for `name`
/// @param name Name for which to unpause the contract
/// @dev The contract must be paused for `name`
function _unpause(bytes32 name) internal {
require(paused[name], "19");
paused[name] = false;
emit Unpaused(name);
}
}
|
Computes the current fees to be taken when minting using `amount` of collateral amount Amount of collateral in the transaction to get stablecoins col Struct for the collateral of interest return feeMint Mint Fees taken to users expressed in collateral Fees depend on the hedge ratio that is the ratio between what is hedged by HAs and what should be hedged The more is hedged by HAs, the smaller fees are expected to be Fees are also corrected by the `bonusMalusMint` parameter which induces a dependence in collateral ratio This is done to avoid an external call in the case where the fees are constant regardless of the collateral ratio Computing the fees based on the spread
|
function _computeFeeMint(uint256 amount, Collateral storage col) internal view returns (uint256 feeMint) {
uint64 feeMint64;
if (col.feeData.xFeeMint.length == 1) {
feeMint64 = col.feeData.yFeeMint[0];
uint64 hedgeRatio = _computeHedgeRatio(amount + col.stocksUsers, col);
feeMint64 = _piecewiseLinear(hedgeRatio, col.feeData.xFeeMint, col.feeData.yFeeMint);
}
}
| 5,974,171 |
pragma solidity 0.8.7;
// SPDX-License-Identifier: MIT
import "./ReentrancyGuard.sol";
import "./SafeMath.sol";
import "./SafeEIP20.sol";
import "./Ownable.sol";
import "./Pausable.sol";
import "./Lockable.sol";
/**
* @title StakePool
* @notice Implements a Ownable, Pausable, Lockable, ReentrancyGuard
*/
contract StakePool is Ownable, Pausable, Lockable, ReentrancyGuard {
using SafeMath for uint256;
using SafeEIP20 for IEIP20;
// We usually require to know who are all the stakeholders.
address[] internal stakeholders;
string[] internal poollist;
uint256 internal currentTimestamp = block.timestamp;
struct Stake {
uint256 amount; // The stake amount
uint256 duration; // The duration in weeks of how long the stake should be locked from unstaking
address referral; // The affiliate address
string pool; // The selected pool
uint256 reward; // The staking reward earned
uint256 reward_paid; // The staking reward paid out so far
uint256 reward_count; // The total amount of times a reward has been distributed
uint256 reward_claimable_after_duration; // The duration in weeks after which a reward can be withdrawn
uint256 bonus; // The referral bonus earned
uint256 bonus_paid; // The referral bonus paid out so far
uint256 bonus_claimable_after_duration; // The duration in weeks after which a bonus can be withdrawn
uint256 bonus_updated_at; // The last time a bonus is updated
uint256 reward_updated_at; // The last time a staking reward is updated
uint256 bonus_last_withdraw_at; // The last time a bonus is withrawn
uint256 reward_last_withdraw_at; // The last time a staking reward is withrawn
uint256 last_withdraw_at; // The last time a stake is withrawn
uint256 created_at; // Timestamp of when stake was created
uint256 updated_at; // Timestamp of when stake was last modified
bool valid; // If a stake is valid or not
}
struct Pool {
string name; // The name of the pool, should be a single word in lowercase
address staking_token; // The staking token address
address reward_token; // The staking reward token address
address bonus_token; // The bonus token address
uint256 duration_in_weeks; // The duration in weeks of the pool
uint256 reward_percentage; // The reward percentage of the pool
uint256 minimum_stake; // The minimum amount a stakeholder can stake
uint256 reward_halving; // Will halve reward every 2 year untill the 6th year if activated
uint256 referral_bonus_percentage; // The referral bonus percentage of the pool
uint256 reward_claimable_after_duration; // The duration in weeks after which a reward can be withdrawn
uint256 bonus_claimable_after_duration; // The duration in weeks after which a bonus can be withdrawn
address default_referral; // The default referral address of the pool
uint256 created_at; // Timestamp of when pool was created
uint256 updated_at; // Timestamp of when pool was last modified
bool valid; // If a pool is valid or not
}
//The stakes for each stakeholder.
mapping(address => Stake) internal stakes;
//The pools for each poollist.
mapping(string => Pool) internal pools;
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
uint256 public balance;
constructor() {
}
receive() payable external {
balance += msg.value;
emit TransferReceived(_msgSender(), msg.value);
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
/* ========== STAKES METHODS ----------
/**
* @notice A method for a stakeholder to create a stake.
* @param amount The size of the stake to be created.
* @param _pool The pool to stake in.
* @param _affiliate An affiliate address to benefit from the stake.
*/
function createStake(uint256 amount, string memory _pool, address _affiliate) external nonReentrant whenNotPaused whenNotLocked {
require(amount > 0, "Insufficient stake amount");
Stake storage stake = stakes[_msgSender()];
if (!stake.valid) {
_isValidPool(_pool);
Pool memory pool = pools[_pool];
require(pool.valid, "Invalid pool");
require(amount >= pool.minimum_stake, "Stake is below minimum allowed stake");
_totalSupply = _totalSupply.add(amount);
_balances[_msgSender()] = _balances[_msgSender()].add(amount);
IEIP20(pool.staking_token).safeTransferFrom(_msgSender(), address(this), amount);
addStakeholder(_msgSender());
stake.amount = stake.amount.add(amount);
stake.pool = _pool;
stake.duration = pool.duration_in_weeks;
stake.reward_claimable_after_duration = pool.reward_claimable_after_duration;
stake.bonus_claimable_after_duration = pool.bonus_claimable_after_duration;
stake.created_at = currentTimestamp;
stake.updated_at = currentTimestamp;
stake.valid = true;
stake.reward = stake.reward.add(0);
stake.reward_count = 0;
stake.bonus = stake.bonus.add(0);
address _referral_address = pool.default_referral;
//check if the referral is a stakeholder and also if _msgSender is not the referral
(bool _isReferralStakeholder,) = isStakeholder(_affiliate);
if (_isReferralStakeholder && _msgSender() != _affiliate){
_referral_address = _affiliate;
}
uint256 referral_bonus = amount / (100 * (10 ** 18));
uint256 affiliate_bonus = referral_bonus.mul(pool.referral_bonus_percentage);
stake.referral = _referral_address;
Stake storage referral_stake = stakes[_referral_address];
referral_stake.bonus = referral_stake.bonus.add(affiliate_bonus);
emit Staked(_msgSender(), amount, pool.name);
}else{
Pool memory pool = pools[stake.pool];
require(pool.valid, "Invalid pool");
_totalSupply = _totalSupply.add(amount);
_balances[_msgSender()] = _balances[_msgSender()].add(amount);
IEIP20(pool.staking_token).safeTransferFrom(_msgSender(), address(this), amount);
stake.amount = stake.amount.add(amount);
stake.updated_at = currentTimestamp;
emit Staked(_msgSender(), amount, pool.name);
}
}
/**
* @notice A method for a stakeholder to remove a stake.
* @param amount The size of the stake to be removed.
*/
function withdraw(uint256 amount) public nonReentrant whenNotPaused whenNotLocked {
require(amount > 0, "Cannot withdraw 0");
Stake storage stake = stakes[_msgSender()];
require(stake.valid, "No stake found.");
Pool memory pool = pools[stake.pool];
require(pool.valid, "Invalid pool");
require(_isExpired(stake.created_at, stake.duration), "You can't withdraw untill the stake duration is over.");
require(stake.amount >= amount, "Insufficient amount of stakes");
stake.amount = stake.amount.sub(amount);
if (stake.amount == 0) removeStakeholder(_msgSender());
_totalSupply = _totalSupply.sub(amount);
_balances[_msgSender()] = _balances[_msgSender()].sub(amount);
IEIP20(pool.staking_token).safeTransfer(_msgSender(), amount);
emit Withdrawn(_msgSender(), amount, stake.pool);
}
/**
* @notice A method to retrieve the stake for a stakeholder.
* @param _stakeholder The stakeholder to retrieve the stake for.
* @return uint256 The amount of wei staked.
*/
function stakeOf(address _stakeholder) public view returns (uint256, string memory) {
require(_stakeholder != address(0), "Invalid stakeholder");
Stake memory stake = stakes[_stakeholder];
require(stake.valid, "No stake found.");
return (stake.amount,stake.pool);
}
/**
* @notice A method to the aggregated stakes from all stakeholders.
* @return uint256 The aggregated stakes from all stakeholders.
*/
function totalStakes() public view returns (uint256) {
uint256 _totalStakes = 0;
for (uint256 s = 0; s < stakeholders.length; s += 1) {
Stake memory stake = stakes[stakeholders[s]];
_totalStakes = _totalStakes.add(stake.amount);
}
return _totalStakes;
}
/**
* @notice A method to check if an address is a stakeholder.
* @param _address The address to verify.
* @return bool, uint256 Whether the address is a stakeholder,
* and if so its position in the stakeholders array.
*/
function isStakeholder(address _address) public view returns (bool, uint256) {
for (uint256 s = 0; s < stakeholders.length; s += 1) {
if (_address == stakeholders[s]) return (true, s);
}
return (false, 0);
}
function exit() external {
withdraw(_balances[_msgSender()]);
getReward();
getBonus();
}
/* ========== REWARD METHODS ========== */
/**
* @notice A method to allow a stakeholder to check his rewards.
* @param _stakeholder The stakeholder to check rewards for.
*/
function rewardOf(address _stakeholder) public view returns (uint256) {
Stake memory stake = stakes[_stakeholder];
return stake.reward;
}
/**
* @notice A method to the aggregated rewards from all stakeholders.
* @return uint256 The aggregated rewards from all stakeholders.
*/
function totalRewards() public view returns (uint256) {
uint256 _totalRewards = 0;
for (uint256 s = 0; s < stakeholders.length; s += 1) {
address stakeholder = stakeholders[s];
Stake memory stake = stakes[stakeholder];
_totalRewards = _totalRewards.add(stake.reward);
}
return _totalRewards;
}
function calculateTotalHalvedReward(address _stakeholder) public view returns (uint256) {
require(_stakeholder != address(0), "Invalid stakeholder");
Stake memory stake = stakes[_stakeholder];
require(stake.valid, "Stake not found");
Pool memory pool = pools[stake.pool];
require(pool.valid, "Invalid pool");
uint256 reward = stake.amount / (100 * (10 ** 18));
uint256 total_reward = reward.mul(pool.reward_percentage);
uint256 total_halved_reward = total_reward;
if(pool.reward_halving > 0){
if (block.timestamp >= pool.created_at + 104 weeks) {
total_halved_reward = total_reward/2;
if(block.timestamp >= pool.created_at + 208 weeks){
total_halved_reward = total_reward/4;
if(block.timestamp >= pool.created_at + 312 weeks){
total_halved_reward = total_reward;
}
}
}
}
return total_halved_reward;
}
/**
* @notice A simple method that calculates the total rewards for each stakeholder.
* @param _stakeholder The stakeholder to calculate rewards for.
*/
function calculateTotalReward(address _stakeholder) public view returns (uint256) {
require(_stakeholder != address(0), "Invalid stakeholder");
Stake memory stake = stakes[_stakeholder];
require(stake.valid, "Stake not found");
Pool memory pool = pools[stake.pool];
require(pool.valid, "Invalid pool");
return calculateTotalHalvedReward(_stakeholder);
}
/**
* @notice A simple method that calculates the weekly rewards for each stakeholder.
* @param _stakeholder The stakeholder to calculate rewards for.
*/
function calculateWeeklyReward(address _stakeholder) public view returns (uint256) {
require(_stakeholder != address(0), "Invalid stakeholder");
Stake memory stake = stakes[_stakeholder];
require(stake.valid, "Stake not found");
Pool memory pool = pools[stake.pool];
require(pool.valid, "Invalid pool");
uint256 total_reward = calculateTotalReward(_stakeholder);
uint256 weekly_reward = total_reward / pool.duration_in_weeks;
return weekly_reward;
}
/**
* @notice A simple method that calculates the daily rewards for each stakeholder.
* @param _stakeholder The stakeholder to calculate rewards for.
*/
function calculateDailyReward(address _stakeholder) public view returns (uint256) {
require(_stakeholder != address(0), "Invalid stakeholder");
Stake memory stake = stakes[_stakeholder];
require(stake.valid, "Stake not found");
Pool memory pool = pools[stake.pool];
require(pool.valid, "Invalid pool");
uint256 weekly_reward = calculateWeeklyReward(_stakeholder);
uint256 daily_reward = weekly_reward / 7;
return daily_reward;
}
/**
* @notice A method to distribute total rewards to all stakeholders.
*/
function distributeTotalRewards() public payable onlyOwner {
uint256 _totalRewards = 0;
for (uint256 s = 0; s < stakeholders.length; s += 1) {
address stakeholder = stakeholders[s];
Stake storage stake = stakes[stakeholder];
if(stake.valid){
uint256 _reward = calculateTotalReward(stakeholder);
uint256 _next_reward_in_days = 7;
uint256 _max_reward_count = stake.duration.mul(_next_reward_in_days);
if (_reward > stake.reward) {
if (stake.reward_count < _max_reward_count) {
stake.reward = _reward;
stake.reward_count = stake.reward_count.add(_max_reward_count);
stake.reward_updated_at = currentTimestamp;
_totalRewards = _totalRewards.add(_reward);
}
}
}
}
emit TotalRewardDistributed(_totalRewards);
}
/**
* @notice A method to distribute weekly rewards to all stakeholders.
*/
function distributeWeeklyRewards() public payable onlyOwner {
uint256 _totalRewards = 0;
for (uint256 s = 0; s < stakeholders.length; s += 1) {
address stakeholder = stakeholders[s];
Stake storage stake = stakes[stakeholder];
if(stake.valid){
uint256 _total_reward = calculateTotalReward(stakeholder);
uint256 _reward = calculateWeeklyReward(stakeholder);
uint256 _next_reward_in_days = 7;
uint256 _check_reward_count_exceeded = stake.reward_count + _next_reward_in_days;
uint256 _max_reward_count = stake.duration.mul(_next_reward_in_days);
//check if staking period for stakeholder has not expired
if (!_isExpired(stake.created_at, stake.duration)) {
if (stake.reward_count < _max_reward_count && _check_reward_count_exceeded <= _max_reward_count && _isExpiredInDays(stake.reward_updated_at, _next_reward_in_days) && _total_reward > stake.reward) {
stake.reward = stake.reward.add(_reward);
stake.reward_count = stake.reward_count.add(_next_reward_in_days);
stake.reward_updated_at = currentTimestamp;
_totalRewards = _totalRewards.add(_reward);
}
}
}
}
emit WeeklyRewardDistributed(_totalRewards);
}
/**
* @notice A method to distribute daily rewards to all stakeholders.
*/
function distributeDailyRewards() public payable onlyOwner {
uint256 _totalRewards = 0;
for (uint256 s = 0; s < stakeholders.length; s += 1) {
address stakeholder = stakeholders[s];
Stake storage stake = stakes[stakeholder];
if(stake.valid){
uint256 _total_reward = calculateTotalReward(stakeholder);
uint256 _reward = calculateDailyReward(stakeholder);
uint256 _next_reward_in_days = 1;
uint256 _check_reward_count_exceeded = stake.reward_count + _next_reward_in_days;
uint256 _max_reward_count = stake.duration.mul(_next_reward_in_days);
//check if staking period for stakeholder has not expired
if (!_isExpired(stake.created_at, stake.duration)) {
if (stake.reward_count < _max_reward_count && _check_reward_count_exceeded <= _max_reward_count && _isExpiredInDays(stake.reward_updated_at, _next_reward_in_days) && _total_reward > stake.reward) {
stake.reward = stake.reward.add(_reward);
stake.reward_count = stake.reward_count.add(_next_reward_in_days);
stake.reward_updated_at = currentTimestamp;
_totalRewards = _totalRewards.add(_reward);
}
}
}
}
emit DailyRewardDistributed(_totalRewards);
}
/**
* @notice A method to allow a stakeholder to withdraw his rewards.
*/
function getReward() public nonReentrant whenNotPaused whenNotLocked {
Stake storage stake = stakes[_msgSender()];
require(stake.valid, "No stake found.");
require(_isExpired(stake.created_at, stake.reward_claimable_after_duration), "Can't withdraw reward until the holding duration is over.");
Pool memory pool = pools[stake.pool];
require(pool.valid, "Invalid pool");
uint256 _reward = stake.reward;
if (_reward > 0) {
IEIP20(pool.reward_token).safeTransfer(_msgSender(), _reward);
stake.reward = 0; //reset amount
stake.reward_count = 0; //reset count
stake.reward_last_withdraw_at = currentTimestamp;
stake.reward_paid = stake.reward_paid.add(_reward);
emit RewardPaid(_msgSender(), _reward);
}
}
/* ========== REFERRAL BONUS METHODS ========== */
/**
* @notice A method to allow a stakeholder to check his bonus.
* @param _stakeholder The stakeholder to check bonus for.
*/
function bonusOf(address _stakeholder) public view returns (uint256) {
Stake memory stake = stakes[_stakeholder];
return stake.bonus;
}
/**
* @notice A method to the aggregated bonuses from all stakeholders.
* @return uint256 The aggregated bonuses from all stakeholders.
*/
function totalBonuses() public view returns (uint256) {
uint256 _totalBonuses = 0;
for (uint256 s = 0; s < stakeholders.length; s += 1) {
address stakeholder = stakeholders[s];
Stake memory stake = stakes[stakeholder];
_totalBonuses = _totalBonuses.add(stake.bonus);
}
return _totalBonuses;
}
/**
* @notice A method to allow a stakeholder to withdraw his bonus.
*/
function getBonus() public nonReentrant whenNotPaused whenNotLocked {
Stake storage stake = stakes[_msgSender()];
require(stake.valid, "No stake found.");
require(_isExpired(stake.created_at, stake.bonus_claimable_after_duration), "Can't withdraw reward until the holding duration is over.");
Pool memory pool = pools[stake.pool];
require(pool.valid, "Invalid pool");
uint256 _bonus = stake.bonus;
if (_bonus > 0) {
IEIP20(pool.bonus_token).safeTransfer(_msgSender(), _bonus);
stake.bonus = 0; //reset amount
stake.bonus_last_withdraw_at = currentTimestamp;
stake.bonus_paid = stake.bonus_paid.add(_bonus);
emit BonusPaid(_msgSender(), _bonus);
}
}
/* ========== POOL METHODS ========== */
/**
* @notice A method for a contract owner to create a staking pool.
* @param _name The name of the pool to be created.
* @param _minimum_stake The minimum a stakeholder can stake.
* @param _duration The duration in weeks of the pool to be created.
* @param _reward_percentage The total reward percentage of the pool to be created
* @param _reward_halving Whether to activate reward halving or not. 1 to activate | 0 to deactivate
* @param _referral_bonus_percentage The referral bonus percentage of the pool to be created
* @param _default_referral The default affiliate address if none is set
* @param _reward_claimable_after When the reward will be claimable after specified weeks
* @param _bonus_claimable_after When the bonus will be claimable after specified weeks
* @param _staking_token The staking token contract address
* @param _reward_token The reward token contract address
* @param _bonus_token The bonus token contract address
*/
function createPool(string memory _name, uint256 _minimum_stake, uint256 _duration, uint256 _reward_percentage, uint256 _reward_halving, uint256 _referral_bonus_percentage, address _default_referral, uint256 _reward_claimable_after, uint256 _bonus_claimable_after, address _staking_token, address _reward_token, address _bonus_token) public onlyOwner {
require(_duration > 0, "Duration in weeks can't be zero");
require(_minimum_stake > 0, "Minimum stake can't be zero");
require(_reward_percentage > 0, "Total reward percentage can't be zero");
Pool storage pool = pools[_name];
if (!pool.valid) {
_addPool(_name);
pool.name = _name;
pool.minimum_stake = _minimum_stake;
pool.duration_in_weeks = _duration;
pool.reward_percentage = _reward_percentage;
pool.reward_halving = (_reward_halving > 0)? 1 : 0;
pool.referral_bonus_percentage = _referral_bonus_percentage;
pool.default_referral = _default_referral;
pool.reward_claimable_after_duration = _reward_claimable_after;
pool.bonus_claimable_after_duration = _bonus_claimable_after;
pool.staking_token = _staking_token;
pool.reward_token = _reward_token;
pool.bonus_token = _bonus_token;
pool.created_at = currentTimestamp;
pool.valid = true;
}
emit PoolAdded(pool.name, _duration);
}
/**
* @notice A method for a contract owner to update a staking pool.
* @param _name The name of the pool to be updated.
* @param _minimum_stake The minimum a stakeholder can stake.
* @param _duration The duration in weeks of the pool to be created.
* @param _reward_percentage The reward percentage of the pool to be created
* @param _reward_halving Whether to activate reward halving or not. 1 to activate | 0 to deactivate
* @param _referral_bonus_percentage The referral bonus percentage of the pool to be created
* @param _default_referral The default affiliate address if none is set
* @param _reward_claimable_after When the reward will be claimable after specified weeks
* @param _bonus_claimable_after When the bonus will be claimable after specified weeks
* @param _staking_token The staking token contract address
* @param _reward_token The reward token contract address
* @param _bonus_token The bonus token contract address
*/
function updatePool(string memory _name, uint256 _minimum_stake, uint256 _duration, uint256 _reward_percentage, uint256 _reward_halving, uint256 _referral_bonus_percentage, address _default_referral, uint256 _reward_claimable_after, uint256 _bonus_claimable_after, address _staking_token, address _reward_token, address _bonus_token) public onlyOwner {
require(_duration > 0, "Duration in weeks can't be zero");
require(_minimum_stake > 0, "Minimum stake can't be zero");
require(_reward_percentage > 0, "Total reward percentage can't be zero");
Pool storage pool = pools[_name];
require(pool.valid, "No pool found.");
pool.name = _name;
pool.minimum_stake = _minimum_stake;
pool.duration_in_weeks = _duration;
pool.reward_percentage = _reward_percentage;
pool.reward_halving = (_reward_halving > 0)? 1 : 0;
pool.referral_bonus_percentage = _referral_bonus_percentage;
pool.default_referral = _default_referral;
pool.reward_claimable_after_duration = _reward_claimable_after;
pool.bonus_claimable_after_duration = _bonus_claimable_after;
pool.staking_token = _staking_token;
pool.reward_token = _reward_token;
pool.bonus_token = _bonus_token;
pool.updated_at = currentTimestamp;
emit PoolUpdated(pool.name, _duration);
}
/**
* @notice A method for a contract owner to remove a staking pool.
* @param _name The name of the pool to be removed.
*/
function removePool(string memory _name) public onlyOwner {
Pool storage pool = pools[_name];
require(pool.valid, "No pool found.");
(bool _isPool, uint256 s) = isPool(_name);
if (_isPool) {
//revert stakeholders stakes before removing the pool
for (uint256 i = 0; i < stakeholders.length; i += 1) {
address _stakeholder = stakeholders[i];
Stake storage stake = stakes[_stakeholder];
uint256 _stake = stake.amount;
stake.amount = stake.amount.sub(_stake);
if (stake.amount == 0) removeStakeholder(_stakeholder);
_totalSupply = _totalSupply.sub(_stake);
_balances[_stakeholder] = _balances[_stakeholder].sub(_stake);
IEIP20(pool.staking_token).safeTransfer(_stakeholder, _stake);
}
delete pools[_name];
poollist[s] = poollist[poollist.length - 1];
poollist.pop();
emit PoolDeleted(pool.name);
}
}
/**
* @notice A method to retrieve the pool with the name.
* @param _name The pool to retrieve
*/
function poolOf(string memory _name) public view returns (string memory, uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, address, address){
Pool memory pool = pools[_name];
require(pool.valid, "No pool found.");
return (pool.name, pool.minimum_stake, pool.duration_in_weeks, pool.reward_percentage, pool.reward_halving,pool.referral_bonus_percentage, pool.reward_claimable_after_duration, pool.bonus_claimable_after_duration, pool.staking_token,pool.reward_token,pool.bonus_token);
}
function poolStakes(string memory _pool) public view returns (uint256) {
uint256 _totalStakes = 0;
for (uint256 s = 0; s < stakeholders.length; s += 1) {
Stake memory stake = stakes[stakeholders[s]];
if(_compareStrings(stake.pool,_pool)){
_totalStakes = _totalStakes.add(stake.amount);
}
}
return _totalStakes;
}
/**
* @notice A method to check if a pool exist.
* @param _name The name to verify.
* @return bool, uint256 Whether the name exist,
* and if so its position in the poollist array.
*/
function isPool(string memory _name) public view returns (bool, uint256) {
for (uint256 s = 0; s < poollist.length; s += 1) {
if (_compareStrings(_name,poollist[s])) return (true, s);
}
return (false, 0);
}
/* ========== UTILS METHODS ========== */
function withdrawNative(uint amount, address payable destAddr) public onlyOwner {
require(amount <= balance, "Insufficient funds");
destAddr.transfer(amount);
balance -= amount;
emit TransferSent(_msgSender(), destAddr, amount);
}
function transferToken(address token, address to, uint256 amount) public onlyOwner {
uint256 EIP20balance = IEIP20(token).balanceOf(address(this));
require(amount <= EIP20balance, "balance is low");
IEIP20(token).safeTransfer(to, amount);
emit TransferSent(_msgSender(), to, amount);
}
function balanceOfToken(address token) public view returns (uint256) {
uint256 tokenBal = IEIP20(token).balanceOf(address(this));
return tokenBal;
}
function balanceOfNative() public view returns (uint256) {
uint256 nativeBal = address(this).balance;
return nativeBal;
}
/* ========== INTERNAL METHODS ========== */
/**
* @notice A method to add a stakeholder.
* @param _stakeholder The stakeholder to add.
*/
function addStakeholder(address _stakeholder) internal {
(bool _isStakeholder,) = isStakeholder(_stakeholder);
if (!_isStakeholder) stakeholders.push(_stakeholder);
}
/**
* @notice A method to remove a stakeholder.
* @param _stakeholder The stakeholder to remove.
*/
function removeStakeholder(address _stakeholder) internal {
(bool _isStakeholder, uint256 s) = isStakeholder(_stakeholder);
if (_isStakeholder) {
stakeholders[s] = stakeholders[stakeholders.length - 1];
stakeholders.pop();
Stake storage stake = stakes[_stakeholder];
stake.valid = false;
}
}
/**
* @notice A method to add a pool.
* @param _name The name to add.
*/
function _addPool(string memory _name) internal {
(bool _isPool,) = isPool(_name);
if (!_isPool) poollist.push(_name);
}
function _isValidPool (string memory _pool) internal view {
(bool _isPool, ) = isPool(_pool);
require(_isPool, "Invalid stake pool");
}
function _compareStrings(string memory _a, string memory _b) internal pure returns (bool) {
return (keccak256(bytes(_a)) == keccak256(bytes(_b)));
}
function _toLower(string memory str) internal pure returns (string memory) {
bytes memory bStr = bytes(str);
bytes memory bLower = new bytes(bStr.length);
for (uint i = 0; i < bStr.length; i++) {
// Uppercase character...
if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) {
// So we add 32 to make it lowercase
bLower[i] = bytes1(uint8(bStr[i]) + 32);
} else {
bLower[i] = bStr[i];
}
}
return string(bLower);
}
function _isExpired(uint256 _time, uint256 _duration) internal view returns(bool){
if (block.timestamp >= _time + _duration * 1 weeks) {
return true;
} else {
return false;
}
}
function _isExpiredInDays(uint256 _time, uint256 _duration) internal view returns(bool){
if (block.timestamp >= _time + _duration * 1 days) {
return true;
} else {
return false;
}
}
/* ========== EVENTS ========== */
event Staked(address indexed sender, uint256 amount, string pool);
event Withdrawn(address indexed sender, uint256 amount, string pool);
event RewardPaid(address indexed user, uint256 reward);
event DailyRewardDistributed(uint256 reward);
event WeeklyRewardDistributed(uint256 reward);
event TotalRewardDistributed(uint256 reward);
event BonusPaid(address indexed user, uint256 bonus);
event PoolAdded(string pool, uint256 duration);
event PoolUpdated(string pool, uint256 duration);
event PoolDeleted(string pool);
event TransferReceived(address _from, uint _amount);
event TransferSent(address _from, address _destAddr, uint _amount);
}
|
A method to remove a stakeholder. _stakeholder The stakeholder to remove./
|
function removeStakeholder(address _stakeholder) internal {
(bool _isStakeholder, uint256 s) = isStakeholder(_stakeholder);
if (_isStakeholder) {
stakeholders[s] = stakeholders[stakeholders.length - 1];
stakeholders.pop();
Stake storage stake = stakes[_stakeholder];
stake.valid = false;
}
}
| 927,719 |
pragma solidity ^0.4.17;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/CryptoCardsCore.sol";
contract TestCardOwnership {
CryptoCardsCore cryptoCards = CryptoCardsCore(DeployedAddresses.CryptoCardsCore());
// Testing the createCard() and ownerOf() function
function testCreateCard() public {
uint expected = cryptoCards.totalSupply();
uint returnedID = cryptoCards.createCard(this, 0);
Assert.equal(returnedID, expected, "Created card should have next sequential cardID");
address cardOwner = cryptoCards.ownerOf(returnedID);
Assert.equal(cardOwner, this, "Created card should be owned by this address");
}
// Testing the balanceOf() function
function testBalanceOf() public {
uint256 balance = cryptoCards.balanceOf(this);
testCreateCard();
Assert.equal(balance+1, cryptoCards.balanceOf(this), "Result of balanceOf changed by an unexpected amount.");
testCreateCard();
Assert.equal(balance+2, cryptoCards.balanceOf(this), "Result of balanceOf changed by an unexpected amount.");
}
// Test creating many additional cards
function testCreateManyCards() public {
uint numCards = 5;
uint expected = cryptoCards.balanceOf(this) + numCards;
uint i = 0;
for (i = 0; i < numCards; i++) {
testCreateCard();
}
uint256 balance = cryptoCards.balanceOf(this);
Assert.equal(balance, expected, "Balance should increase to expected count after creating many cards");
}
// Testing the tokensOfOwner() function
/*function testTokensOfOwner() public {
uint256[] memoryownerTokens = cryptoCards.tokensOfOwner(this);
Assert.equal(ownerTokens.length, 1, "Test should own one token via tokensOfOwner");
}*/
}
|
Testing the balanceOf() function
|
function testBalanceOf() public {
uint256 balance = cryptoCards.balanceOf(this);
testCreateCard();
Assert.equal(balance+1, cryptoCards.balanceOf(this), "Result of balanceOf changed by an unexpected amount.");
testCreateCard();
Assert.equal(balance+2, cryptoCards.balanceOf(this), "Result of balanceOf changed by an unexpected amount.");
}
| 1,016,997 |
./full_match/1/0xc0543F481549a93745090e87bCCBEb9FbcBEF4e9/sources/contracts/OracleValiIndexTools.sol
|
Inspired by OraclizeAPI's implementation - MIT licence https:github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
|
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
| 5,016,851 |
./partial_match/1/0xA54E7C2dD1b46740276293DD9DC37F8d019bcfDB/sources/PeachRoyalNFTV1.sol
|
Indicates that this contract supports both ERC721Metadata, and ERC2981 interfaces/
|
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721A, ERC2981, AccessControlEnumerable)
returns (bool)
{
return ERC721A.supportsInterface(interfaceId) || ERC2981.supportsInterface(interfaceId);
}
| 15,565,113 |
pragma solidity 0.4.21;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev revert()s if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* Math operations with safety checks
*/
library SafeMath {
function mul256(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div256(uint256 a, uint256 b) internal returns (uint256) {
require(b > 0); // Solidity automatically revert()s when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub256(uint256 a, uint256 b) internal returns (uint256) {
require(b <= a);
return a - b;
}
function add256(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant public returns (uint256);
function transfer(address to, uint256 value) public;
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev ERC20 interface with allowances.
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant public returns (uint256);
function transferFrom(address from, address to, uint256 value) public;
function approve(address spender, uint256 value) public;
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4);
_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public {
balances[msg.sender] = balances[msg.sender].sub256(_value);
balances[_to] = balances[_to].add256(_value);
Transfer(msg.sender, _to, _value);
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant public returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
* @dev Implemantation of the basic standart token.
*/
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already revert() if this condition is not met
// if (_value > _allowance) revert();
balances[_to] = balances[_to].add256(_value);
balances[_from] = balances[_from].sub256(_value);
allowed[_from][msg.sender] = _allowance.sub256(_value);
Transfer(_from, _to, _value);
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public {
// To change the approve amount you first have to reduce the addresses
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert();
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens than an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title TeuToken
* @dev The main TEU token contract
*
*/
contract TeuToken is StandardToken, Ownable{
string public name = "20-footEqvUnit";
string public symbol = "TEU";
uint public decimals = 18;
event TokenBurned(uint256 value);
function TeuToken() public {
totalSupply = (10 ** 8) * (10 ** decimals);
balances[msg.sender] = totalSupply;
}
/**
* @dev Allows the owner to burn the token
* @param _value number of tokens to be burned.
*/
function burn(uint _value) onlyOwner public {
require(balances[msg.sender] >= _value);
balances[msg.sender] = balances[msg.sender].sub256(_value);
totalSupply = totalSupply.sub256(_value);
TokenBurned(_value);
}
}
/**
* @title teuInitialTokenSale
* @dev The TEU token ICO contract
*
*/
contract teuInitialTokenSale is Ownable {
using SafeMath for uint256;
event LogContribution(address indexed _contributor, uint256 _etherAmount, uint256 _basicTokenAmount, uint256 _timeBonusTokenAmount, uint256 _volumeBonusTokenAmount);
event LogContributionBitcoin(address indexed _contributor, uint256 _bitcoinAmount, uint256 _etherAmount, uint256 _basicTokenAmount, uint256 _timeBonusTokenAmount, uint256 _volumeBonusTokenAmount, uint _contributionDatetime);
event LogOffChainContribution(address indexed _contributor, uint256 _etherAmount, uint256 _tokenAmount);
event LogReferralAward(address indexed _refereeWallet, address indexed _referrerWallet, uint256 _referralBonusAmount);
event LogTokenCollected(address indexed _contributor, uint256 _collectedTokenAmount);
event LogClientIdentRejectListChange(address indexed _contributor, uint8 _newValue);
TeuToken constant private token = TeuToken(0xeEAc3F8da16bb0485a4A11c5128b0518DaC81448); // hard coded due to token already deployed
address constant private etherHolderWallet = 0x00222EaD2D0F83A71F645d3d9634599EC8222830; // hard coded due to deployment for once only
uint256 constant private minContribution = 100 finney;
uint public saleStart = 1523498400;
uint public saleEnd = 1526090400;
uint constant private etherToTokenConversionRate = 400;
uint constant private referralAwardPercent = 20;
uint256 constant private maxCollectableToken = 20 * 10 ** 6 * 10 ** 18;
mapping (address => uint256) private referralContribution; // record the referral contribution amount in ether for claiming of referral bonus
mapping (address => uint) private lastContribitionDate; // record the last contribution date/time for valid the referral bonus claiming period
mapping (address => uint256) private collectableToken; // record the token amount to be collected of each contributor
mapping (address => uint8) private clientIdentRejectList; // record a list of contributors who do not pass the client identification process
bool public isCollectTokenStart = false; // flag to indicate if token collection is started
bool public isAllowContribution = true; // flag to enable/disable contribution.
uint256 public totalCollectableToken; // the total amount of token will be colleceted after considering all the contribution and bonus
// ***** private helper functions ***************
/**
* @dev get the current datetime
*/
function getCurrentDatetime() private constant returns (uint) {
return now;
}
/**
* @dev get the current sale day
*/
function getCurrentSaleDay() private saleIsOn returns (uint) {
return getCurrentDatetime().sub256(saleStart).div256(86400).add256(1);
}
/**
* @dev to get the time bonus Percentage based on the no. of sale day(s)
* @param _days no of sale day to calculate the time bonus
*/
function getTimeBonusPercent(uint _days) private pure returns (uint) {
if (_days <= 10)
return 50;
return 0;
}
/**
* @dev to get the volumne bonus percentage based on the ether amount contributed
* @param _etherAmount ether amount contributed.
*/
function getVolumeBonusPercent(uint256 _etherAmount) private pure returns (uint) {
if (_etherAmount < 1 ether)
return 0;
if (_etherAmount < 2 ether)
return 35;
if (_etherAmount < 3 ether)
return 40;
if (_etherAmount < 4 ether)
return 45;
if (_etherAmount < 5 ether)
return 50;
if (_etherAmount < 10 ether)
return 55;
if (_etherAmount < 20 ether)
return 60;
if (_etherAmount < 30 ether)
return 65;
if (_etherAmount < 40 ether)
return 70;
if (_etherAmount < 50 ether)
return 75;
if (_etherAmount < 100 ether)
return 80;
if (_etherAmount < 200 ether)
return 90;
if (_etherAmount >= 200 ether)
return 100;
return 0;
}
/**
* @dev to get the time bonus amount given the token amount to be collected from contribution
* @param _tokenAmount token amount to be collected from contribution
*/
function getTimeBonusAmount(uint256 _tokenAmount) private returns (uint256) {
return _tokenAmount.mul256(getTimeBonusPercent(getCurrentSaleDay())).div256(100);
}
/**
* @dev to get the volume bonus amount given the token amount to be collected from contribution and the ether amount contributed
* @param _tokenAmount token amount to be collected from contribution
* @param _etherAmount ether amount contributed
*/
function getVolumeBonusAmount(uint256 _tokenAmount, uint256 _etherAmount) private returns (uint256) {
return _tokenAmount.mul256(getVolumeBonusPercent(_etherAmount)).div256(100);
}
/**
* @dev to get the referral bonus amount given the ether amount contributed
* @param _etherAmount ether amount contributed
*/
function getReferralBonusAmount(uint256 _etherAmount) private returns (uint256) {
return _etherAmount.mul256(etherToTokenConversionRate).mul256(referralAwardPercent).div256(100);
}
/**
* @dev to get the basic amount of token to be collected given the ether amount contributed
* @param _etherAmount ether amount contributed
*/
function getBasicTokenAmount(uint256 _etherAmount) private returns (uint256) {
return _etherAmount.mul256(etherToTokenConversionRate);
}
// ****** modifiers ************
/**
* @dev modifier to allow contribution only when the sale is ON
*/
modifier saleIsOn() {
require(getCurrentDatetime() >= saleStart && getCurrentDatetime() < saleEnd);
_;
}
/**
* @dev modifier to check if the sale is ended
*/
modifier saleIsEnd() {
require(getCurrentDatetime() >= saleEnd);
_;
}
/**
* @dev modifier to check if token is collectable
*/
modifier tokenIsCollectable() {
require(isCollectTokenStart);
_;
}
/**
* @dev modifier to check if contribution is over the min. contribution amount
*/
modifier overMinContribution(uint256 _etherAmount) {
require(_etherAmount >= minContribution);
_;
}
/**
* @dev modifier to check if max. token pool is not reached
*/
modifier underMaxTokenPool() {
require(maxCollectableToken > totalCollectableToken);
_;
}
/**
* @dev modifier to check if contribution is allowed
*/
modifier contributionAllowed() {
require(isAllowContribution);
_;
}
// ***** public transactional functions ***************
/**
* @dev called by owner to set the new sale start date/time
* @param _newStart new start date/time
*/
function setNewStart(uint _newStart) public onlyOwner {
require(saleStart > getCurrentDatetime());
require(_newStart > getCurrentDatetime());
require(saleEnd > _newStart);
saleStart = _newStart;
}
/**
* @dev called by owner to set the new sale end date/time
* @param _newEnd new end date/time
*/
function setNewEnd(uint _newEnd) public onlyOwner {
require(saleEnd < getCurrentDatetime());
require(_newEnd < getCurrentDatetime());
require(_newEnd > saleStart);
saleEnd = _newEnd;
}
/**
* @dev called by owner to enable / disable contribution
* @param _isAllow true - allow contribution; false - disallow contribution
*/
function enableContribution(bool _isAllow) public onlyOwner {
isAllowContribution = _isAllow;
}
/**
* @dev called by contributors to record a contribution
*/
function contribute() public payable saleIsOn overMinContribution(msg.value) underMaxTokenPool contributionAllowed {
uint256 _basicToken = getBasicTokenAmount(msg.value);
uint256 _timeBonus = getTimeBonusAmount(_basicToken);
uint256 _volumeBonus = getVolumeBonusAmount(_basicToken, msg.value);
uint256 _totalToken = _basicToken.add256(_timeBonus).add256(_volumeBonus);
lastContribitionDate[msg.sender] = getCurrentDatetime();
referralContribution[msg.sender] = referralContribution[msg.sender].add256(msg.value);
collectableToken[msg.sender] = collectableToken[msg.sender].add256(_totalToken);
totalCollectableToken = totalCollectableToken.add256(_totalToken);
assert(etherHolderWallet.send(msg.value));
LogContribution(msg.sender, msg.value, _basicToken, _timeBonus, _volumeBonus);
}
/**
* @dev called by contract owner to record a off chain contribution by Bitcoin. The token collection process is the same as those ether contributors
* @param _bitcoinAmount bitcoin amount contributed
* @param _etherAmount ether equivalent amount contributed
* @param _contributorWallet wallet address of contributor which will be used for token collection
* @param _contributionDatetime date/time of contribution. For calculating time bonus and claiming referral bonus.
*/
function contributeByBitcoin(uint256 _bitcoinAmount, uint256 _etherAmount, address _contributorWallet, uint _contributionDatetime) public overMinContribution(_etherAmount) onlyOwner contributionAllowed {
require(_contributionDatetime <= getCurrentDatetime());
uint256 _basicToken = getBasicTokenAmount(_etherAmount);
uint256 _timeBonus = getTimeBonusAmount(_basicToken);
uint256 _volumeBonus = getVolumeBonusAmount(_basicToken, _etherAmount);
uint256 _totalToken = _basicToken.add256(_timeBonus).add256(_volumeBonus);
if (_contributionDatetime > lastContribitionDate[_contributorWallet])
lastContribitionDate[_contributorWallet] = _contributionDatetime;
referralContribution[_contributorWallet] = referralContribution[_contributorWallet].add256(_etherAmount);
collectableToken[_contributorWallet] = collectableToken[_contributorWallet].add256(_totalToken);
totalCollectableToken = totalCollectableToken.add256(_totalToken);
LogContributionBitcoin(_contributorWallet, _bitcoinAmount, _etherAmount, _basicToken, _timeBonus, _volumeBonus, _contributionDatetime);
}
/**
* @dev called by contract owner to record a off chain contribution by Ether. The token are distributed off chain already. The contributor can only entitle referral bonus through this smart contract
* @param _etherAmount ether equivalent amount contributed
* @param _contributorWallet wallet address of contributor which will be used for referral bonus collection
* @param _tokenAmount amunt of token distributed to the contributor. For reference only in the event log
*/
function recordOffChainContribute(uint256 _etherAmount, address _contributorWallet, uint256 _tokenAmount) public overMinContribution(_etherAmount) onlyOwner {
lastContribitionDate[_contributorWallet] = getCurrentDatetime();
LogOffChainContribution(_contributorWallet, _etherAmount, _tokenAmount);
}
/**
* @dev called by contributor to claim the referral bonus
* @param _referrerWallet wallet address of referrer. Referrer must also be a contributor
*/
function referral(address _referrerWallet) public {
require (msg.sender != _referrerWallet);
require (referralContribution[msg.sender] > 0);
require (lastContribitionDate[_referrerWallet] > 0);
require (getCurrentDatetime() - lastContribitionDate[msg.sender] <= (4 * 24 * 60 * 60));
uint256 _referralBonus = getReferralBonusAmount(referralContribution[msg.sender]);
referralContribution[msg.sender] = 0;
collectableToken[msg.sender] = collectableToken[msg.sender].add256(_referralBonus);
collectableToken[_referrerWallet] = collectableToken[_referrerWallet].add256(_referralBonus);
totalCollectableToken = totalCollectableToken.add256(_referralBonus).add256(_referralBonus);
LogReferralAward(msg.sender, _referrerWallet, _referralBonus);
}
/**
* @dev called by contract owener to register a list of rejected clients who cannot pass the client identification process.
* @param _clients an array of wallet address clients to be set
* @param _valueToSet 1 - add to reject list, 0 - remove from reject list
*/
function setClientIdentRejectList(address[] _clients, uint8 _valueToSet) public onlyOwner {
for (uint i = 0; i < _clients.length; i++) {
if (_clients[i] != address(0) && clientIdentRejectList[_clients[i]] != _valueToSet) {
clientIdentRejectList[_clients[i]] = _valueToSet;
LogClientIdentRejectListChange(_clients[i], _valueToSet);
}
}
}
/**
* @dev called by contract owner to enable / disable token collection process
* @param _enable true - enable collection; false - disable collection
*/
function setTokenCollectable(bool _enable) public onlyOwner saleIsEnd {
isCollectTokenStart = _enable;
}
/**
* @dev called by contributor to collect tokens. If they are rejected by the client identification process, error will be thrown
*/
function collectToken() public tokenIsCollectable {
uint256 _collToken = collectableToken[msg.sender];
require(clientIdentRejectList[msg.sender] <= 0);
require(_collToken > 0);
collectableToken[msg.sender] = 0;
token.transfer(msg.sender, _collToken);
LogTokenCollected(msg.sender, _collToken);
}
/**
* @dev Allow owner to transfer out the token left in the contract
* @param _to address to transfer to
* @param _amount amount to transfer
*/
function transferTokenOut(address _to, uint256 _amount) public onlyOwner {
token.transfer(_to, _amount);
}
/**
* @dev Allow owner to transfer out the ether left in the contract
* @param _to address to transfer to
* @param _amount amount to transfer
*/
function transferEtherOut(address _to, uint256 _amount) public onlyOwner {
assert(_to.send(_amount));
}
// ***** public constant functions ***************
/**
* @dev to get the amount of token collectable by any contributor
* @param _contributor contributor to get amont
*/
function collectableTokenOf(address _contributor) public constant returns (uint256) {
return collectableToken[_contributor] ;
}
/**
* @dev to get the amount of token collectable by any contributor
* @param _contributor contributor to get amont
*/
function isClientIdentRejectedOf(address _contributor) public constant returns (uint8) {
return clientIdentRejectList[_contributor];
}
/**
* @dev Fallback function which receives ether and create the appropriate number of tokens for the
* msg.sender.
*/
function() external payable {
contribute();
}
}
|
Allow owner to transfer out the ether left in the contract _to address to transfer to _amount amount to transfer/
|
function transferEtherOut(address _to, uint256 _amount) public onlyOwner {
assert(_to.send(_amount));
}
| 500,646 |
pragma solidity >=0.8.0 <0.9.0;
//SPDX-License-Identifier: MIT
import "hardhat/console.sol";
import "./ExampleExternalContract.sol";
// import "./IterableMapping.sol";
contract Staker {
// using IterableMapping for IterableMapping.Map;
ExampleExternalContract public exampleExternalContract;
mapping(address => uint256) public balances;
// IterableMapping.Map private balancesMap;
uint256 public constant threshold = 0.1 ether;
uint256 public deadline = block.timestamp + 72 hours;
bool public openForWithdraw = false;
bool public locked;
constructor(address exampleExternalContractAddress) public {
exampleExternalContract = ExampleExternalContract(exampleExternalContractAddress);
}
// EVENTS
event Stake(address staker, uint256 value);
event Complete(uint256 amount);
event Withdraw(address _to, uint256 value);
// MODIFIERS
modifier notCompleted() {
require(!locked, "Not Completed!");
locked = true;
_;
locked = false;
}
// Collect funds in a payable `stake()` function and track individual `balances` with a mapping:
// ( make sure to add a `Stake(address,uint256)` event and emit it for the frontend <List/> display )
function stake() public payable {
require(timeLeft() > 0, "Deadline has been reached, No more staking");
// Set the maps:
balances[msg.sender] = balances[msg.sender] + msg.value;
// balancesMap.set(msg.sender, balancesMap.get(msg.sender) + msg.value);
emit Stake(msg.sender, msg.value);
if (address(this).balance >= threshold) {
// We're over threshold so emit the complete event and transfer to complete()
emit Complete(address(this).balance);
exampleExternalContract.complete{ value: address(this).balance }();
}
}
// function getBalancesAddresses() public view returns (address[] memory) {
// return balancesMap.keys;
// }
// After some `deadline` allow anyone to call an `execute()` function
// It should either call `exampleExternalContract.complete{value: address(this).balance}()` to send all the value
function execute() public notCompleted {
// If we've reached the deadline, check if we've met the threshold
if (timeLeft() == 0) {
// if the `threshold` was not met, allow everyone to call a `withdraw()` function
if (address(this).balance >= threshold) {
// We're over threshold so emit the complete event and transfer to complete()
emit Complete(address(this).balance);
exampleExternalContract.complete{ value: address(this).balance }();
} else {
openForWithdraw = true;
}
}
}
// Add a `timeLeft()` view function that returns the time left before the deadline for the frontend
function timeLeft() public view returns (uint256) {
if (block.timestamp >= deadline) {
return 0;
} else {
return deadline - block.timestamp;
}
}
// Allow stakers to withdraw if openForWithdraw
function withdraw(address payable _to) public notCompleted {
require(openForWithdraw == true, "Not open for withdrawals");
require(balances[_to] > 1 wei, "Must have at least 1 wei balance");
// Send the balance for _to back to _to
(bool sent, bytes memory data) = _to.call{ value: balances[_to] }("");
require(sent, "Failed to withdraw() Ether");
// Emit an event indicating sucess and set balance to 0
emit Withdraw(_to, balances[_to]);
// Update the Mappings
balances[_to] = 0;
// balancesMap.remove(_to);
}
// Add the `receive()` special function that receives eth and calls stake()
receive() external payable {
stake();
}
}
|
Allow stakers to withdraw if openForWithdraw Send the balance for _to back to _to Emit an event indicating sucess and set balance to 0 Update the Mappings balancesMap.remove(_to);
|
function withdraw(address payable _to) public notCompleted {
require(openForWithdraw == true, "Not open for withdrawals");
require(balances[_to] > 1 wei, "Must have at least 1 wei balance");
require(sent, "Failed to withdraw() Ether");
emit Withdraw(_to, balances[_to]);
balances[_to] = 0;
}
| 2,464,397 |
./full_match/4/0x1CB311f9a68c486144FB7eDA3359c581A17EC6F0/sources/HATVaults.sol
|
todo : should the hacker split rewards can be updated ?
|
function setRewardsSplit(uint256 _pid, uint256[4] memory _rewardsSplit)
external
onlyGovernance {
require(
_rewardsSplit[0]+
_rewardsSplit[1]+
_rewardsSplit[2]+
_rewardsSplit[3] < REWARDS_LEVEL_DENOMINATOR,
"total split % should be less than 10000");
poolsRewards[_pid].hackerRewardSplit = _rewardsSplit[0];
poolsRewards[_pid].approverRewardSplit = _rewardsSplit[1];
poolsRewards[_pid].swapAndBurnSplit = _rewardsSplit[2];
poolsRewards[_pid].hackerHatRewardSplit = _rewardsSplit[3];
emit SetRewardsSplit(_pid, _rewardsSplit);
}
| 813,292 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "./Ownable.sol";
/// @title Graveyard NFT Project's URN Token Interface
/// @author @0xyamyam
interface IUrn {
function mint(address to, uint256 amount) external;
}
/// @title Graveyard NFT Project's Rewardable Token Interface
/// @author @0xyamyam
interface IRewardable {
function getCommittalReward(address to) external view returns (uint256);
function getRewardRate(address to) external view returns (uint256);
}
/// @title Graveyard NFT Project's CRYPT Token
/// @author @0xyamyam
/// CRYPT's are the centerpiece of the Graveyard NFT project.
contract Graveyard is IERC721Receiver, ReentrancyGuard, Ownable(5, true, false) {
using SafeMath for uint256;
/// 0 = inactive, 1 = accepting tokens for whitelist, 2 = whitelist mint, 3 = public
uint256 public _releaseStage;
uint256 public _startRewarding;
/// URN address
address public _urnAddress;
/// Contracts able to generate rewards
address[] public _rewardingContracts;
/// URN rewards per address
mapping(address => uint256) private _claimable;
mapping(address => uint256) private _claimUpdated;
/// Whitelisted addresses
mapping(address => uint256) public _whitelist;
/// Event for use in the crypt
event Committed(address indexed from, address indexed contractAddress, uint256 indexed tokenId, bytes data);
/// Event for release stage changing
event ReleaseStage(uint256);
/// Rewarding contracts are allowed to update rewards for addresses
modifier onlyRewarding {
bool authorised = false;
address sender = _msgSender();
for (uint256 i = 0;i < _rewardingContracts.length;i++) {
if (_rewardingContracts[i] == sender) {
authorised = true;
break;
}
}
require(authorised, "Unauthorized");
_;
}
/// Determine the release stage
function releaseStage() external view returns (uint256) {
return _releaseStage;
}
/// Determine if the address is whitelisted
/// @param from The address to check
/// @param qty The qty to check for
function isWhitelisted(address from, uint256 qty) external view returns (bool) {
return _whitelist[from] >= qty;
}
/// The pending URN claim for address
/// @param from The address to check for rewards
/// @notice Rewards only claimable after reward claiming starts
function claimable(address from) public view returns (uint256) {
return _claimable[from] + _getPendingClaim(from);
}
/// Claim rewards from the graveyard
function claim() external nonReentrant {
require(_startRewarding != 0 && _urnAddress != address(0), "Rewards unavailable");
address sender = _msgSender();
uint256 amount = claimable(sender);
require(amount > 0, "Nothing to claim");
_claimable[sender] = 0;
_claimUpdated[sender] = block.timestamp;
IUrn(_urnAddress).mint(sender, amount);
}
/// Provide a batch transfer option for users with many tokens to commit.
/// @param contracts Array of ERC721 contracts to batch transfer
/// @param tokenIds Array of arrays of tokenIds matched to the contracts array
/// @param data Array of arrays of bytes messages for each committed token matched to the contracts array
/// @notice Sender MUST setApprovalForAll for this contract address on the contracts being supplied,
/// this means to be efficient you will need to transfer 3 or more tokens from the contract to be worth it.
function commitTokens(
address[] calldata contracts, uint256[][] calldata tokenIds, bytes[][] calldata data
) external nonReentrant {
require(contracts.length == tokenIds.length && tokenIds.length == data.length, "Invalid args");
address sender = _msgSender();
for (uint256 i = 0;i < contracts.length;i++) {
IERC721 token = IERC721(contracts[i]);
for (uint256 j = 0;j < tokenIds[i].length;j++) {
token.safeTransferFrom(sender, address(this), tokenIds[i][j], data[i][j]);
}
}
}
/// Sets contract properties which control stages of the release.
/// @param stage The stage of release
/// @param contracts The rewarding contracts
function setState(uint256 stage, address[] calldata contracts) external onlyOwner {
_releaseStage = stage;
_rewardingContracts = contracts;
emit ReleaseStage(stage);
}
/// Set URN contract and and implicitly start rewards
/// @param urnAddress URN contract
function startRewards(address urnAddress) external onlyOwner {
_urnAddress = urnAddress;
_startRewarding = block.timestamp;
}
/// Update the whitelist amount for an address to prevent multiple mints in future
/// @param from The whitelist address
/// @param qty How many to remove from total
function updateWhitelist(address from, uint256 qty) external onlyRewarding nonReentrant {
_whitelist[from] -= qty;
}
/// Update the rewards for an address, this includes any pending rewards and updates the timestamp
/// @param from The address for rewards
/// @param qty The total to add to rewards
function updateClaimable(address from, uint256 qty) external onlyRewarding nonReentrant {
if (_startRewarding == 0) {
_claimable[from] += qty;
} else {
_claimable[from] += qty + _getPendingClaim(from);
_claimUpdated[from] = block.timestamp;
}
}
/// Instead of storing data on-chain for who sent what NFT's we emit events which can be queried later on.
/// This is more efficient as event storage is significantly cheaper.
/// If the sender owns a URN rewarding token (CRYPT) rewards are calculated.
/// @inheritdoc IERC721Receiver
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4) {
uint256 stage = _releaseStage;
require(stage == 1 || stage > 2, "Cannot accept");
emit Committed(from, _msgSender(), tokenId, data);
if (stage == 1) {
_whitelist[from] = 3;
} else {
uint256 amount = 0;
for (uint256 i = 0;i < _rewardingContracts.length;i++) {
amount += IRewardable(_rewardingContracts[i]).getCommittalReward(from);
}
_claimable[from] += amount;
}
return this.onERC721Received.selector;
}
/// Calculates the pending reward from rewarding contracts.
/// URN rewards are calculated daily off the rate defined by rewarding contracts.
/// @param from The address to calculate rewards for
function _getPendingClaim(address from) internal view returns (uint256) {
if (_startRewarding == 0) return 0;
uint256 rate = 0;
for (uint256 i = 0;i < _rewardingContracts.length;i++) {
rate += IRewardable(_rewardingContracts[i]).getRewardRate(from);
}
uint256 startFrom = _claimUpdated[from] == 0 ? _startRewarding : _claimUpdated[from];
return rate * (block.timestamp - startFrom) / 1 days;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
/// @title ENS main interface to fetch the resolver for a name
interface IENS {
function resolver(bytes32 node) external view returns (IResolver);
}
/// @title ENS resolver to address interface
interface IResolver {
function addr(bytes32 node) external view returns (address);
}
/// @title Graveyard NFT Project's ENSOwnable implementation
/// @author [email protected]
/// Contract ownership is tied to an ens token, once set the resolved address of the ens name is the contract owner.
abstract contract Ownable is Context {
using SafeERC20 for IERC20;
using SafeMath for uint256;
/// Apply a fee to release funds sent to the contract
/// A very small price to pay for being able to regain tokens incorrectly sent here
uint256 private _releaseFee;
/// Configure if this contract allows release
bool private _releasesERC20;
bool private _releasesERC721;
/// Ownership is set to the contract creator until a nameHash is set
address private _owner;
/// The ENS namehash who controls the contracts
bytes32 public _nameHash;
/// @dev Initializes the contract setting the deployer as the initial owner
constructor(uint256 releaseFee, bool releasesERC20, bool releasesERC721) {
_owner = _msgSender();
_releaseFee = releaseFee;
_releasesERC20 = releasesERC20;
_releasesERC721 = releasesERC721;
}
/// @dev Returns the address of the current owner
function owner() public view virtual returns (address) {
if (_nameHash == "") return _owner;
bytes32 node = _nameHash;
IENS ens = IENS(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e);
IResolver resolver = ens.resolver(node);
return resolver.addr(node);
}
/// @dev Throws if called by any account other than the owner
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/// Set the ENS name as owner
/// @param nameHash The bytes32 hash of the ens name
function setNameHash(bytes32 nameHash) external onlyOwner {
_nameHash = nameHash;
}
/// Return ERC20 tokens sent to the contract, an optional fee is automatically applied.
/// @notice If your reading this you are very lucky, most tokens sent to contracts can never be recovered.
/// @param token The ERC20 token address
/// @param to The address to send funds to
/// @param amount The amount of tokens to send (minus any fee)
function releaseERC20(IERC20 token, address to, uint256 amount) external onlyOwner {
require(_releasesERC20, "Not allowed");
require(token.balanceOf(address(this)) >= amount, "Insufficient balance");
uint share = 100;
if (_releaseFee > 0) token.safeTransfer(_msgSender(), amount.mul(_releaseFee).div(100));
token.safeTransfer(to, amount.mul(share.sub(_releaseFee)).div(100));
}
/// Return ERC721 tokens sent to the contract, a fee may be required.
/// @notice If your reading this you are very lucky, most tokens sent to contracts can never be recovered.
/// @param tokenAddress The ERC721 token address
/// @param to The address to the send the token to
/// @param tokenId The ERC721 tokenId to send
function releaseERC721(IERC721 tokenAddress, address to, uint256 tokenId) external onlyOwner {
require(_releasesERC721, "Not allowed");
require(tokenAddress.ownerOf(tokenId) == address(this), "Invalid tokenId");
tokenAddress.safeTransferFrom(address(this), to, tokenId);
}
/// Withdraw eth from contract.
/// @dev many contracts are guarded by default against this, but should a contract have receive/fallback methods
/// a bug could be introduced that make this a great help.
function withdraw() external virtual onlyOwner {
payable(_msgSender()).call{value: address(this).balance}("");
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
Returns the address of the current owner
|
function owner() public view virtual returns (address) {
if (_nameHash == "") return _owner;
bytes32 node = _nameHash;
IENS ens = IENS(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e);
IResolver resolver = ens.resolver(node);
return resolver.addr(node);
}
| 614,996 |
pragma solidity 0.6.12;
interface IERC20 {
function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB877(a, b, "SafeMath: subtraction overflow");
}
function SUB877(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL487(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV156(a, b, "SafeMath: division by zero");
}
function DIV156(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD860(a, b, "SafeMath: modulo by zero");
}
function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT107(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function SENDVALUE513(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value));
}
function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value));
}
function SAFEAPPROVE765(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE946(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value));
}
function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value);
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN137(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).ISCONTRACT107(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
if (!_CONTAINS837(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING
return set._indexes[value] != 0;
}
function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING
return set._values.length;
}
function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD286(set._inner, bytes32(uint256(value)));
}
function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE863(set._inner, bytes32(uint256(value)));
}
function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS837(set._inner, bytes32(uint256(value)));
}
function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH639(set._inner);
}
function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING
return address(uint256(_AT524(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD286(set._inner, bytes32(value));
}
function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE863(set._inner, bytes32(value));
}
function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS837(set._inner, bytes32(value));
}
function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH639(set._inner);
}
function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING
return uint256(_AT524(set._inner, index));
}
}
contract Initializable {
bool private initialized;
bool private initializing;
modifier INITIALIZER933() { //inject NONSTANDARD NAMING
require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
function ISCONSTRUCTOR543() private view returns (bool) { //inject NONSTANDARD NAMING
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __CONTEXT_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED28();
}
function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING
}
function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA356() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED28();
__OWNABLE_INIT_UNCHAINED19();
}
function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING
address msgSender = _MSGSENDER195();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED637(address(0), msgSender);
}
function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER691() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED637(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED637(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
interface INBUNIERC20 {
function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
event LOG470(string log); //inject NONSTANDARD NAMING
}
library console {
address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING
function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING
uint256 payloadLength = payload.length;
address consoleAddress = console_address243;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function LOG714() internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log()"));
}
function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0));
}
function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0));
}
function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0));
}
function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0));
}
function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0));
}
function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0));
}
function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0));
}
function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0));
}
function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0));
}
function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0));
}
function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0));
}
function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0));
}
function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0));
}
function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0));
}
function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0));
}
function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0));
}
function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0));
}
function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0));
}
function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0));
}
function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0));
}
function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0));
}
function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0));
}
function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0));
}
function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0));
}
function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0));
}
function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0));
}
function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0));
}
function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0));
}
function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0));
}
function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0));
}
function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0));
}
function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0));
}
function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0));
}
function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0));
}
function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0));
}
function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0));
}
function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0));
}
function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0));
}
function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0));
}
function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0));
}
function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0));
}
function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0));
}
function LOG714(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0));
}
function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// HDCore Vault distributes fees equally amongst staked pools
// Have fun reading it. Hopefully it's bug-free. God bless.
contract HdcoreVault is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of HdCOREs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws tokens to a pool. Here's what happens:
// 1. The pool's `accHdcorePerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block.
uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
mapping(address => mapping(address => uint256)) allowance;
}
// The HDCORE TOKEN!
INBUNIERC20 public hdcore;
// Dev address.
address public devaddr;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
// Returns fees generated since start of this contract
function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING
averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock));
}
// Returns averge fees in this epoch
function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING
averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock));
}
// For easy graphing historical epoch rewards
mapping(uint => uint256) public epochRewards;
//Starts a new calculation epoch
// Because averge since start will not be accurate
function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING
require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week
epochRewards[epoch] = rewardsInThisEpoch;
cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch);
rewardsInThisEpoch = 0;
epochCalculationStartBlock = block.number;
++epoch;
}
event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING
address indexed user,
uint256 indexed pid,
uint256 amount
);
event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING
function INITIALIZE896( //inject NONSTANDARD NAMING
INBUNIERC20 _hdcore
) public INITIALIZER933 {
OwnableUpgradeSafe.__OWNABLE_INIT503();
DEV_FEE = 724;
hdcore = _hdcore;
devaddr = msg.sender;
contractStartBlock = block.number;
_superAdmin = msg.sender;
}
function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING
return poolInfo.length;
}
// Add a new token pool. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function ADD659( //inject NONSTANDARD NAMING
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
bool _withdrawable
) public ONLYOWNER691 {
if (_withUpdate) {
MASSUPDATEPOOLS941();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token,"Error pool already added");
}
totalAllocPoint = totalAllocPoint.ADD659(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accHdcorePerShare: 0,
withdrawable : _withdrawable
})
);
}
// Update the given pool's HDCOREs allocation point. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function SET408( //inject NONSTANDARD NAMING
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public ONLYOWNER691 {
if (_withUpdate) {
MASSUPDATEPOOLS941();
}
totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update the given pool's ability to withdraw tokens
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING
uint256 _pid,
bool _withdrawable
) public ONLYOWNER691 {
poolInfo[_pid].withdrawable = _withdrawable;
}
// Sets the dev fee for this contract
// defaults at 7.24%
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
uint16 DEV_FEE;
function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING
require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%');
DEV_FEE = _DEV_FEE;
}
uint256 pending_DEV_rewards;
// View function to see pending HDCOREs on frontend.
function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accHdcorePerShare = pool.accHdcorePerShare;
return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING
console.LOG714("Mass Updating Pools");
uint256 length = poolInfo.length;
uint allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.ADD659(UPDATEPOOL374(pid));
}
pendingRewards = pendingRewards.SUB877(allRewards);
}
// ----
// Function that adds pending rewards, called by the HDCORE token.
// ----
uint256 private hdcoreBalance;
function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING
uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance);
if(newRewards > 0) {
hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change
pendingRewards = pendingRewards.ADD659(newRewards);
rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards);
}
}
// Update reward variables of the given pool to be up-to-date.
function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.BALANCEOF536(address(this));
if (tokenSupply == 0) { // avoids division by 0 errors
return 0;
}
hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation
.MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get
.DIV156(totalAllocPoint); // we can do this because pools are only mass updated
uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000);
uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee);
pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee);
pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659(
hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply)
);
}
// Deposit tokens to HdcoreVault for HDCORE allocation.
function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
MASSUPDATEPOOLS941();
// Transfer pending tokens
// to user
UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender);
//Transfer in the amounts from user
// save gas
if(_amount > 0) {
pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount);
user.amount = user.amount.ADD659(_amount);
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit DEPOSIT941(msg.sender, _pid, _amount);
}
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
// requires no allowances
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][depositFor];
MASSUPDATEPOOLS941();
// Transfer pending tokens
// to user
UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for
if(_amount > 0) {
pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount);
user.amount = user.amount.ADD659(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit DEPOSIT941(depositFor, _pid, _amount);
}
// Test coverage
// [x] Does allowance update correctly?
function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
pool.allowance[msg.sender][spender] = value;
emit APPROVAL172(msg.sender, spender, _pid, value);
}
// Test coverage
// [x] Does allowance decrease?
// [x] Do oyu need allowance
// [x] Withdraws to correct address
function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance");
pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount);
_WITHDRAW26(_pid, _amount, owner, msg.sender);
}
// Withdraw tokens from HdcoreVault.
function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
_WITHDRAW26(_pid, _amount, msg.sender, msg.sender);
}
// Low level withdraw function
function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][from];
require(user.amount >= _amount, "withdraw: not good");
MASSUPDATEPOOLS941();
UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed
if(_amount > 0) {
user.amount = user.amount.SUB877(_amount);
pool.token.SAFETRANSFER239(address(to), _amount);
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit WITHDRAW483(to, _pid, _amount);
}
function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
MASSUPDATEPOOLS941();
UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender);
}
function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING
if(user.amount == 0) return;
uint256 pending = user
.amount
.MUL487(pool.accHdcorePerShare)
.DIV156(1e12)
.SUB877(user.rewardDebt);
if(pending > 0) {
SAFEHDCORETRANSFER939(from, pending);
}
}
// function that lets owner/governance contract
// approve allowance for any token inside this contract
// This means all future UNI like airdrops are covered
// And at the same time allows us to give allowance to strategy contracts.
// Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked
function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD");
require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks
IERC20(tokenAddress).APPROVE926(contractAddress, _amount);
}
function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
// !Caution this will remove all your pending rewards!
function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.SAFETRANSFER239(address(msg.sender), user.amount);
emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
// No mass update dont update pending rewards
}
// Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs.
function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING
if(_amount == 0) return;
uint256 hdcoreBal = hdcore.BALANCEOF536(address(this));
if (_amount > hdcoreBal) {
console.LOG714("transfering out for to person:", _amount);
console.LOG714("Balance of this address is :", hdcoreBal);
hdcore.TRANSFER353(_to, hdcoreBal);
hdcoreBalance = hdcore.BALANCEOF536(address(this));
} else {
hdcore.TRANSFER353(_to, _amount);
hdcoreBalance = hdcore.BALANCEOF536(address(this));
}
if(pending_DEV_rewards > 0) {
uint256 devSend = pending_DEV_rewards; // Avoid recursive loop
pending_DEV_rewards = 0;
SAFEHDCORETRANSFER939(devaddr, devSend);
}
}
// Update dev address by the previous dev.
// Note onlyOwner functions are meant for the governance contract
// allowing HDCORE governance token holders to do this functions.
function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING
devaddr = _devaddr;
}
address private _superAdmin;
event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING
return _superAdmin;
}
modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING
require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin.");
_;
}
// Assisns super admint to address 0, making it unreachable forever
function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
emit SUPERADMINTRANSFERED362(_superAdmin, address(0));
_superAdmin = address(0);
}
// Super admin can transfer its powers to another address
function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit SUPERADMINTRANSFERED362(_superAdmin, newOwner);
_superAdmin = newOwner;
}
}
|
inject NONSTANDARD NAMING
|
function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view {
| 14,087,956 |
pragma solidity ^0.4.21;
import "./open-zeppelin/ownership/Ownable.sol";
import "./open-zeppelin/token/ERC20/ERC20.sol";
import "./Fund.sol";
// @title FundWallet
// @dev The FundWallet represents one of the basic building blocks of managing Ether and tokens within the fund.
// Basically the contract is a basic ERC20 compatible wallet which has some small adjustments to integrate better
// with the Fund contract.
// @author ScJa
contract FundWallet is Ownable {
// @dev Event for logging an Ether Transfer
// @param to Address to which the Ether is sent to
// @param value Amount sent in the course of the Ether transfer
// @param balance Remaining balance of wallet after the transfer in wei
event EtherSent(address indexed to, uint256 value, uint256 balance);
// @dev Event for logging when Ether is received by the wallet
// @param from Address from which the Ether was sent
// @param value Amount received
// @param balance Balance of the wallet after receiving value
event Received(address indexed from, uint256 value, uint256 balance);
// @dev Event for logging when a token transfer is requested
// @param token Address to the ERC20-compatible token of which tokens are sent
// @param to Address to which the tokens are sent to
// @param value Amount of tokens sent
event TokensSent(address indexed token, address indexed to, uint256 value);
// @dev Slightly adjusted ownership modifier because the fund itself is also a fund wallet. This allows it to
// to send funds by calling function within this class internally
modifier onlyOwnerOrInternal() {
require(msg.sender == owner || msg.sender == address(this));
_;
}
// @dev Checks if address_ is the zero address
// @param _address Address to check
modifier notNull(address _address) {
require(_address != 0);
_;
}
// @dev Simple constructor which allows to specify a different owner then the msg.sender
// @param _owner Address which will be set to be the owner of this wallet
function FundWallet(address _owner)
public
notNull(_owner)
{
owner = _owner;
}
// @dev Function which initiates a simple Ether transfer. It is adjusted to work well with Fund class
// @param _to Address to which Ether is sent
// @param _value Amount of wei sent
function sendEther(address _to, uint256 _value)
public
onlyOwnerOrInternal
notNull(_to)
{
require(_value > 0);
// Special behaviour here which increases usability for the Fund by avoiding accidental payments instead of
// purchasing tokens.
if (_to == owner) {
Fund fund = Fund(_to);
fund.addFunds.value(_value)();
} else {
// External call
_to.transfer(_value);
}
emit EtherSent(_to, _value, address(this).balance);
}
// @dev Function which initiates a simple token transfer
// @param _token ERC20 compatible token of which tokens are sent
// @param _to Address to which tokens are sent to
// @param _value Amount of token sent
function sendTokens(ERC20 _token, address _to, uint256 _value)
public
onlyOwnerOrInternal
notNull(_to)
{
require(_value > 0);
// External call
require(_token.transfer(_to, _value));
emit TokensSent(_token, _to, _value);
}
// @dev Default payable function which logs any Ether recieved
function ()
public
payable
{
emit Received(msg.sender, msg.value, address(this).balance);
}
}
|
Function which initiates a simple Ether transfer. It is adjusted to work well with Fund class _to Address to which Ether is sent _value Amount of wei sent Special behaviour here which increases usability for the Fund by avoiding accidental payments instead of purchasing tokens. External call
|
function sendEther(address _to, uint256 _value)
public
onlyOwnerOrInternal
notNull(_to)
{
require(_value > 0);
if (_to == owner) {
Fund fund = Fund(_to);
fund.addFunds.value(_value)();
_to.transfer(_value);
}
emit EtherSent(_to, _value, address(this).balance);
}
| 5,361,575 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "./ERC721A.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract FlungNFT is ERC721A, Ownable {
using Strings for uint256;
uint256 public constant WHITELIST_MAX = 5;
uint256 public constant RESERVE_MAX = 2;
uint256 public constant TOTAL_MAX = 12;
uint256 public constant MAX_SALE_QUANTITY = 3;
uint256 public whitelistPrice = 0.01 ether;
uint256 public whitelistCount;
uint256 public reserveCount;
uint32 public startTime;
bool public saleActive;
bool public whitelistActive;
bool private whitelistEnded;
struct DAVariables {
uint64 saleStartPrice;
uint64 duration;
uint64 interval;
uint64 decreaseRate;
}
DAVariables public daVariables;
mapping(address => uint256) public whitelists;
string private baseURI;
bool public revealed;
address private paymentAddress;
address private royaltyAddress;
uint96 private royaltyBasisPoints = 810;
bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
constructor() ERC721A("FashionNFT", "FNFT") {}
/**
* @notice not locked modifier
*/
modifier notEnded() {
require(!whitelistEnded, "WHITELIST_ENDED");
_;
}
/**
* @notice mint from whitelist
* @dev must occur before public sale
*/
function mintWhitelist(uint256 _quantity) external payable notEnded {
require(whitelistActive, "WHITELIST_INACTIVE");
uint256 remaining = whitelists[msg.sender];
require(whitelistCount + _quantity <= WHITELIST_MAX, "WHITELIST_MAXED");
require(remaining != 0 && _quantity <= remaining, "UNAUTHORIZED");
require(msg.value == whitelistPrice * _quantity, "INCORRECT_ETH");
if (_quantity == remaining) {
delete whitelists[msg.sender];
} else {
whitelists[msg.sender] = whitelists[msg.sender] - _quantity;
}
whitelistCount = whitelistCount + _quantity;
_safeMint(msg.sender, _quantity);
}
/**
* @notice buy from sale (dutch auction)
* @dev must occur after whitelist sale
*/
function buy(uint256 _quantity) external payable {
require(saleActive, "SALE_INACTIVE");
require(tx.origin == msg.sender, "NOT_EOA");
require(
_numberMinted(msg.sender) + _quantity <= MAX_SALE_QUANTITY,
"QUANTITY_MAXED"
);
require(
(totalSupply() - reserveCount) + _quantity <=
TOTAL_MAX - RESERVE_MAX,
"SALE_MAXED"
);
uint256 mintCost;
DAVariables memory _daVariables = daVariables;
if (block.timestamp - startTime >= _daVariables.duration) {
mintCost = whitelistPrice * _quantity;
} else {
uint256 steps = (block.timestamp - startTime) /
_daVariables.interval;
mintCost =
(daVariables.saleStartPrice -
(steps * _daVariables.decreaseRate)) *
_quantity;
}
require(msg.value >= mintCost, "INSUFFICIENT_ETH");
_mint(msg.sender, _quantity, "", true);
if (msg.value > mintCost) {
payable(msg.sender).transfer(msg.value - mintCost);
}
}
/**
* @notice release reserve
*/
function releaseReserve(address _account, uint256 _quantity)
external
onlyOwner
{
require(_quantity > 0, "INVALID_QUANTITY");
require(reserveCount + _quantity <= RESERVE_MAX, "RESERVE_MAXED");
reserveCount = reserveCount + _quantity;
_safeMint(_account, _quantity);
}
/**
* @notice return number of tokens minted by owner
*/
function saleMax() external view returns (uint256) {
if (!whitelistEnded) {
return TOTAL_MAX - RESERVE_MAX - WHITELIST_MAX;
}
return TOTAL_MAX - RESERVE_MAX - whitelistCount;
}
/**
* @notice return number of tokens minted by owner
*/
function numberMinted(address owner) external view returns (uint256) {
return _numberMinted(owner);
}
/**
* @notice return current sale price
*/
function getCurrentPrice() external view returns (uint256) {
if (!saleActive) {
return daVariables.saleStartPrice;
}
DAVariables memory _daVariables = daVariables;
if (block.timestamp - startTime >= _daVariables.duration) {
return whitelistPrice;
} else {
uint256 steps = (block.timestamp - startTime) /
_daVariables.interval;
return
daVariables.saleStartPrice -
(steps * _daVariables.decreaseRate);
}
}
/**
* @notice active whitelist
*/
function activateWhitelist() external onlyOwner {
!whitelistActive ? whitelistActive = true : whitelistActive = false;
}
/**
* @notice active sale
*/
function activateSale() external onlyOwner {
require(daVariables.saleStartPrice != 0, "SALE_VARIABLES_NOT_SET");
if (!whitelistEnded) whitelistEnded = true;
if (whitelistActive) whitelistActive = false;
if (startTime == 0) {
startTime = uint32(block.timestamp);
}
!saleActive ? saleActive = true : saleActive = false;
}
/**
* @notice set sale startTime
*/
function setSaleVariables(
uint32 _startTime,
uint64 _saleStartPrice,
uint64 _duration,
uint64 _interval,
uint64 _decreaseRate
) external onlyOwner {
require(!saleActive);
startTime = _startTime;
daVariables = DAVariables({
saleStartPrice: _saleStartPrice,
duration: _duration,
interval: _interval,
decreaseRate: _decreaseRate
});
}
/**
* @notice set base URI
*/
function setBaseURI(string calldata _baseURI, bool reveal) external onlyOwner {
if (!revealed && reveal) revealed = reveal;
baseURI = _baseURI;
}
/**
* @notice set payment address
*/
function setPaymentAddress(address _paymentAddress) external onlyOwner {
paymentAddress = _paymentAddress;
}
/**
* @notice set royalty address
*/
function setRoyaltyAddress(address _royaltyAddress) external onlyOwner {
royaltyAddress = _royaltyAddress;
}
/**
* @notice set royalty rate
*/
function setRoyalty(uint96 _royaltyBasisPoints) external onlyOwner {
royaltyBasisPoints = _royaltyBasisPoints;
}
/**
* @notice set whitelist price
*/
function setWhitelistPrice(uint256 _newPrice) external onlyOwner {
whitelistPrice = _newPrice;
}
/**
* @notice add addresses to whitelist
*/
function setWhitelist(address[] calldata whitelisters, bool ogStatus)
external
onlyOwner
{
uint256 quantity = ogStatus ? 2 : 1;
for (uint256 i; i < whitelisters.length; i++) {
whitelists[whitelisters[i]] = quantity;
}
}
/**
* @notice token URI
*/
function tokenURI(uint256 _tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(_tokenId), "Cannot query non-existent token");
if (revealed) {
return string(abi.encodePacked(baseURI, _tokenId.toString()));
} else{
return baseURI;
}
}
/**
* @notice royalty information
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
require(_exists(_tokenId), "Cannot query non-existent token");
return (royaltyAddress, (_salePrice * royaltyBasisPoints) / 10000);
}
/**
* @notice supports interface
* @dev overridden for EIP2981 royalties
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721A)
returns (bool)
{
if (interfaceId == _INTERFACE_ID_ERC2981) {
return true;
}
return super.supportsInterface(interfaceId);
}
/**
* @notice transfer funds
*/
function transferFunds() external onlyOwner {
(bool success, ) = payable(paymentAddress).call{
value: address(this).balance
}("");
require(success, "TRANSFER_FAILED");
}
}
// SPDX-License-Identifier: MIT
// Creator: Chiru Labs
pragma solidity ^0.8.4;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol';
import '@openzeppelin/contracts/utils/Address.sol';
import '@openzeppelin/contracts/utils/Context.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import '@openzeppelin/contracts/utils/introspection/ERC165.sol';
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintedQueryForZeroAddress();
error BurnedQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerIndexOutOfBounds();
error OwnerQueryForNonexistentToken();
error TokenIndexOutOfBounds();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128).
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
}
// Compiler will pack the following
// _currentIndex and _burnCounter into a single 256bit word.
// The tokenId of the next token to be minted.
uint128 internal _currentIndex;
// The number of tokens burned.
uint128 internal _burnCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex times
unchecked {
return _currentIndex - _burnCounter;
}
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
uint256 numMintedSoFar = _currentIndex;
uint256 tokenIdsIdx;
// Counter overflow is impossible as the loop breaks when
// uint256 i is equal to another uint256 numMintedSoFar.
unchecked {
for (uint256 i; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (!ownership.burned) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
}
revert TokenIndexOutOfBounds();
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds();
uint256 numMintedSoFar = _currentIndex;
uint256 tokenIdsIdx;
address currOwnershipAddr;
// Counter overflow is impossible as the loop breaks when
// uint256 i is equal to another uint256 numMintedSoFar.
unchecked {
for (uint256 i; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
}
// Execution should never reach this point.
revert();
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
if (owner == address(0)) revert MintedQueryForZeroAddress();
return uint256(_addressData[owner].numberMinted);
}
function _numberBurned(address owner) internal view returns (uint256) {
if (owner == address(0)) revert BurnedQueryForZeroAddress();
return uint256(_addressData[owner].numberBurned);
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return '';
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
if (operator == _msgSender()) revert ApproveToCaller();
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
_transfer(from, to, tokenId);
if (!_checkOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < _currentIndex && !_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1
// updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
for (uint256 i; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
updatedIndex++;
}
_currentIndex = uint128(updatedIndex);
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**128.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**128.
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred 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
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
set whitelist price/
|
function setWhitelistPrice(uint256 _newPrice) external onlyOwner {
whitelistPrice = _newPrice;
}
| 5,963,148 |
./full_match/5/0x074C6E4185904075B74eb325b5126711d305185c/sources/contracts/StonksVault.sol
|
claims all rewards for DANK and KALM Want to keep
|
function claim(uint256 _index, address _account)
public
nonReentrant
returns (uint256, uint256)
{
require(
msg.sender == _account || msg.sender == address(this),
"not allowed"
);
updateRewards(_index, _account);
uint256 pendingDank = userRewards[_index][_account];
require(pendingDank > 0, "no pending rewards");
uint256 pendingKalm = pendingKalmRewards(_index, _account);
PoolInfo storage pool = poolInfo[_index];
UserInfo storage user = userInfo[_index][_account];
user.lockEndedTimestamp = block.timestamp + poolInfo[_index].lockDuration;
user.lockStartedTimestamp = block.timestamp;
userRewards[_index][_account] = 0;
user.prevPoolRewards = pool.accDankRewards;
if (lastRebaseBlock != block.number) {
dank.rebase(
block.number,
compound(1e18, debaseRate, block.number - lastRebaseBlock) - 1e18,
false
);
lastRebaseBlock = block.number;
for (uint256 i = 0; i < pairs.length; i++) {
pairs[i].sync();
}
}
dank.mint(_account, pendingDank);
if (address(kalm) != address(0)) {
kalm.mint(_account, pendingKalm);
}
emit RewardPaid(_account, _index, pendingDank, pendingKalm);
return (pendingDank, pendingKalm);
}
| 7,043,877 |
./full_match/421613/0xA4A34B69AA7Bdec4B2656485A299813fF854Cd05/sources/project_/src/active/app/CrossChainBridge.sol
|
Override receive cross-chain message Perform logic based on package type
|
function _nonblockingLzReceive(
uint16 _srcChainId,
bytes memory _payload
) internal virtual override {
uint16 packetType;
assembly {
packetType := mload(add(_payload, 32))
}
if (packetType == PT_SWAP) {
_swapAck(_srcChainId, _payload);
_textAck(_srcChainId, _payload);
revert("Bridge: unknown packet type");
}
}
| 11,569,882 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./AnonymiceLibrary.sol";
import "./ERC721A.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract GenFrens is ERC721A, Ownable {
using AnonymiceLibrary for uint8;
struct Trait {
string traitName;
string traitType;
}
//Mappings
mapping(uint256 => Trait[]) public traitTypes;
mapping(string => bool) hashToMinted;
mapping(uint256 => string) internal tokenIdToHash;
mapping(address => bool) addressMinted;
//uint256s
uint256 MAX_SUPPLY = 444;
uint256 SEED_NONCE = 0;
uint256 MINT_COST = 0.01 ether;
//minting flag
bool public MINTING_LIVE = false;
//uint arrays
uint16[][6] TIERS;
//p5js url
string p5jsUrl;
string p5jsIntegrity;
string imageUrl;
string externalUrl;
constructor() ERC721A("GenFrens", "GENF", 2) {
//Declare all the rarity tiers
//pCol
TIERS[0] = [1400, 1400, 1800, 700, 700, 1800, 1100, 1100];
//sCol
TIERS[1] = [1500, 1800, 900, 900, 1200, 1800, 1500, 400];
//noise Max
TIERS[2] = [4000, 3000, 2000, 1000];
//eyeSize
TIERS[3] = [2500, 5000, 2500];
//Thickness
TIERS[4] = [6000, 2500, 1500];
//eyeLevel
TIERS[5] = [6000, 4000];
}
/*
__ __ _ _ _ ___ _ _
| \/ (_)_ _| |_(_)_ _ __ _ | __| _ _ _ __| |_(_)___ _ _ ___
| |\/| | | ' \ _| | ' \/ _` | | _| || | ' \/ _| _| / _ \ ' \(_-<
|_| |_|_|_||_\__|_|_||_\__, | |_| \_,_|_||_\__|\__|_\___/_||_/__/
|___/
*/
/**
* @dev Converts a digit from 0 - 10000 into its corresponding rarity based on the given rarity tier.
* @param _randinput The input from 0 - 10000 to use for rarity gen.
* @param _rarityTier The tier to use.
*/
function rarityGen(uint256 _randinput, uint8 _rarityTier)
internal
view
returns (uint8)
{
uint16 currentLowerBound = 0;
for (uint8 i = 0; i < TIERS[_rarityTier].length; i++) {
uint16 thisPercentage = TIERS[_rarityTier][i];
if (
_randinput >= currentLowerBound &&
_randinput < currentLowerBound + thisPercentage
) return i;
currentLowerBound = currentLowerBound + thisPercentage;
}
revert();
}
/**
* @dev Generates a 11 digit hash from a tokenId, address, and random number.
* @param _t The token id to be used within the hash.
* @param _a The address to be used within the hash.
* @param _c The custom nonce to be used within the hash.
*/
function hash(
uint256 _t,
address _a,
uint256 _c
) internal returns (string memory) {
require(_c < 11);
// This will generate a 11 character string.
// The first 2 digits are the palette.
string memory currentHash = "";
for (uint8 i = 0; i < 6; i++) {
SEED_NONCE++;
uint16 _randinput = uint16(
uint256(
keccak256(
abi.encodePacked(
block.timestamp,
block.difficulty,
_t,
_a,
_c,
SEED_NONCE
)
)
) % 10000
);
currentHash = string(
abi.encodePacked(
currentHash,
rarityGen(_randinput, i).toString()
)
);
}
if (hashToMinted[currentHash]) return hash(_t, _a, _c + 1);
return currentHash;
}
/**
* @dev Mint internal, this is to avoid code duplication.
*/
function mintInternal(uint8 mintAmount) internal {
require(
MINTING_LIVE == true || msg.sender == owner(),
"Minting not live"
);
uint256 _totalSupply = totalSupply();
require(_totalSupply < MAX_SUPPLY);
require(!AnonymiceLibrary.isContract(msg.sender));
require(addressMinted[msg.sender] != true, "Address already minted");
require(msg.value >= MINT_COST * mintAmount, "Insufficient ETH sent");
for (uint8 i = 0; i < mintAmount; i++) {
uint256 thisTokenId = _totalSupply + i;
tokenIdToHash[thisTokenId] = hash(thisTokenId, msg.sender, 0);
hashToMinted[tokenIdToHash[thisTokenId]] = true;
}
addressMinted[msg.sender] = true;
_safeMint(msg.sender, mintAmount);
}
/**
* @dev Mints new tokens.
*/
function mintFren(uint8 mintAmount) public payable {
return mintInternal(mintAmount);
}
/*
____ ___ ____ ___ _____ __ __ ____ __ ______ ____ ___ ____ _____
| \ / _] / || \ | || | || \ / ] || |/ \ | \ / ___/
| D ) / [_ | o || \ | __|| | || _ | / /| | | || || _ ( \_
| / | _]| || D | | |_ | | || | |/ / |_| |_| | || O || | |\__ |
| \ | [_ | _ || | | _] | : || | / \_ | | | || || | |/ \ |
| . \| || | || | | | | || | \ | | | | || || | |\ |
|__|\_||_____||__|__||_____| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___|
*/
/**
* @dev Hash to HTML function
*/
function hashToHTML(string memory _hash, uint256 _tokenId)
public
view
returns (string memory)
{
string memory htmlString = string(
abi.encodePacked(
"data:text/html,%3Chtml%3E%3Chead%3E%3Cscript%20src%3D%22",
p5jsUrl,
"%22%20integrity%3D%22",
p5jsIntegrity,
"%22%20crossorigin%3D%22anonymous%22%3E%3C%2Fscript%3E%3C%2Fhead%3E%3Cbody%3E%3Cscript%3Evar%20tokenId%3D",
AnonymiceLibrary.toString(_tokenId),
"%3Bvar%20hash%3D%22",
_hash,
"%22%3B"
)
);
htmlString = string(
abi.encodePacked(
htmlString,
"xo%3D1%2Csd%3D21%2AtokenId%2CpCs%3D%5B0%2C30%2C80%2C120%2C180%2C225%2C270%2C300%5D%2CsCs%3D%5B0%2C30%2C120%2C180%2C225%2C270%2C300%2C330%5D%2CnMV%3D%5B.5%2C1%2C2%2C3%5D%2CeSs%3D%5B.26%2C.33%2C.4%5D%2CtV%3D%5B10%2C25%2C70%5D%2CeLs%3D%5B0%2C15%5D%3Bfunction%20setup%28%29%7BcreateCanvas%28500%2C500%29%2CcolorMode%28HSB%2C360%2C100%2C100%29%2CstrokeCap%28ROUND%29%2CnoiseSeed%28sd%29%2CrandomSeed%28sd%29%2CpC%3DparseInt%28hash.substring%280%2C1%29%29%2CsC%3DparseInt%28hash.substring%281%2C2%29%29%2CnM%3DparseInt%28hash.substring%282%2C3%29%29%2CeS%3DparseInt%28hash.substring%283%2C4%29%29%2Ct%3DparseInt%28hash.substring%284%2C5%29%29%2CeL%3DparseInt%28hash.substring%285%2C6%29%29%2C330%3D%3DsCs%5BsC%5D%3Fk%3DpCs%5BpC%5D%3Ak%3DsCs%5BsC%5D%2CwP%3Drandom%285%2C10%29%2ChP%3Drandom%285%2C10%29%7Dfunction%20draw%28%29%7Bbackground%28255%29%3Bfor%28let%20s%3D25%3Bs%3C500%3Bs%2B%3D50%29for%28let%20e%3D25%3Be%3C500%3Be%2B%3D50%29noStroke%28%29%2Cf%3DsCs%5BsC%5D%2C330%3D%3Df%3FrC%3Drandom%28360%29%3ArC%3Dk%2Cfill%28rC%2Crandom%2825%29%2C100%29%2Cc%3Dnew%20C1%2Cpush%28%29%2Ctranslate%28s%2Ce%29%2Cscale%28.14%2C.14%29%2Cc.s%28%29%2Cpop%28%29%3Bc1%3Dnew%20C2%28pCs%5BpC%5D%2C40%2C100%2C0%29%2Cpush%28%29%2Ctranslate%28250%2C500%29%2Crotate%283.14%29%2Cscale%28.55%2C1.25%29%2Cc1.s%28%29%2Cpop%28%29%2Cpush%28%29%2Ctranslate%28250%2C250%29%2Cc1.s%28%29%2Cpop%28%29%2CnoStroke%28%29%2Ce1%3Dnew%20C2%280%2C0%2C100%2C1%29%2Cpush%28%29%2Ctranslate%28200%2C200%29%2Cscale%28.33%29%2Ce1.s%28%29%2Cpop%28%29%2Ce2%3Dnew%20C2%280%2C0%2C100%2C1%29%2Cpush%28%29%2Cpush%28%29%2Ctranslate%28300%2C200%29%2Cscale%28eSs%5BeS%5D%29%2Crotate%28PI%29%2Ce2.s%28%29%2Cpop%28%29%2Cp1%3Dnew%20C2%28k%2C100%2C100%2C1%29%2Cpush%28%29%2Ctranslate%28200%2C200%2BeLs%5BeL%5D%29%2Cscale%28.1%29%2Cp1.s%28%29%2Cpop%28%29%2Cp2%3Dnew%20C2%28k%2C100%2C100%2C1%29%2Cpush%28%29%2Ctranslate%28300%2C200-eLs%5BeL%5D%29%2Cscale%28.1%29%2Crotate%28PI%29%2Cp2.s%28%29%2Cpop%28%29%3Bfor%28let%20s%3D200%3Bs%3C%3D300%3Bs%2B%2B%29sats%3Dmap%28noise%28xo%29%2C0%2C1%2C30%2C100%29%2Cfill%28k%2Csats%2C95%29%2Cr%3Dmap%28noise%28xo%29%2C0%2C1%2C.53%2C.77%29%2Cellipse%28s%2C500%2Ar%2C28%29%2Cxo%2B%3D.015%3BnoLoop%28%29%7Dclass%20C1%7Bs%28%29%7BbeginShape%28%29%3Bfor%28let%20s%3D0%3Bs%3CTWO_PI%3Bs%2B%3D.16%29%7Blet%20e%3Dmap%28cos%28s%29%2C-1%2C1%2C0%2CnMV%5BnM%5D%29%2Ct%3Dmap%28sin%28s%29%2C-1%2C1%2C0%2CnMV%5BnM%5D%29%2Cn%3Dmap%28noise%28e%2Ct%29%2C0%2C1%2C100%2C200%29%2Ca%3Dn%2Acos%28s%29%2Cp%3Dn%2Asin%28s%29%3Bvertex%28a%2Cp%29%2Ce%2B%3D.004%7DendShape%28%29%7D%7Dclass%20C2%7Bconstructor%28s%2Ce%2Ct%2Cn%29%7Bthis.h%3Ds%2Cthis.z%3De%2Cthis.l%3Dt%2Cthis.b%3Dn%7Ds%28%29%7BbeginShape%28%29%2CnoFill%28%29%3Bfor%28let%20s%3D0%3Bs%3CTWO_PI%3Bs%2B%3D.045%29%7Blet%20e%3Dmap%28sin%28s%29%2C-1%2C1%2C0%2CnMV%5BnM%5D%29%2Cn%3Dmap%28cos%28s%29%2C-1%2C1%2C0%2CnMV%5BnM%5D%29%2Ca%3Dmap%28noise%28n%2Ce%29%2C0%2C1%2C100%2C200%29%2Cp%3Da%2Acos%28s%29%2Co%3Da%2Asin%28s%29%3B0%3D%3Dthis.b%26%26%28stroke%28this.h%2Cthis.z%2Cthis.l-25%29%2CstrokeWeight%28tV%5Bt%5D%29%29%2Cvertex%28p%2Co%29%2CendShape%28%29%2Cpush%28%29%2Cstroke%28this.h%2Cthis.z%2Cthis.l%29%2CstrokeWeight%286%29%2Cline%28p%2B7.5%2Co%2B10%2C500%2FwP%2C500%2FhP%29%2Cpop%28%29%2Cn%2B%3D.04%2Ce%2B%3D.001%7DendShape%28%29%7D%7D%3C%2Fscript%3E%3C%2Fbody%3E%3C%2Fhtml%3E"
)
);
return htmlString;
}
/**
* @dev Hash to metadata function
*/
function hashToMetadata(string memory _hash)
public
view
returns (string memory)
{
string memory metadataString;
for (uint8 i = 0; i < 6; i++) {
uint8 thisTraitIndex = AnonymiceLibrary.parseInt(
AnonymiceLibrary.substring(_hash, i, i + 1)
);
metadataString = string(
abi.encodePacked(
metadataString,
'{"trait_type":"',
traitTypes[i][thisTraitIndex].traitType,
'","value":"',
traitTypes[i][thisTraitIndex].traitName,
'"}'
)
);
if (i != 5)
metadataString = string(abi.encodePacked(metadataString, ","));
}
return string(abi.encodePacked("[", metadataString, "]"));
}
/**
* @dev Returns the SVG and metadata for a token Id
* @param _tokenId The tokenId to return the SVG and metadata for.
*/
function tokenURI(uint256 _tokenId)
public
view
override
returns (string memory)
{
require(_exists(_tokenId));
string memory tokenHash = _tokenIdToHash(_tokenId);
string
memory description = '", "description": "444 GenFrens to keep you company. Metadata & images mirrored on chain permanently. Your GenFren will never leave you <3",';
string memory encodedTokenId = AnonymiceLibrary.encode(
bytes(string(abi.encodePacked(AnonymiceLibrary.toString(_tokenId))))
);
string memory encodedHash = AnonymiceLibrary.encode(
bytes(string(abi.encodePacked(tokenHash)))
);
return
string(
abi.encodePacked(
"data:application/json;base64,",
AnonymiceLibrary.encode(
bytes(
string(
abi.encodePacked(
'{"name": "GenFrens #',
AnonymiceLibrary.toString(_tokenId),
description,
'"external_url":"',
externalUrl,
encodedTokenId,
"&t=",
encodedHash,
'","image":"',
imageUrl,
AnonymiceLibrary.toString(_tokenId),
"&t=",
tokenHash,
'","attributes":',
hashToMetadata(tokenHash),
"}"
)
)
)
)
)
);
}
/**
* @dev Returns a hash for a given tokenId
* @param _tokenId The tokenId to return the hash for.
*/
function _tokenIdToHash(uint256 _tokenId)
public
view
returns (string memory)
{
string memory tokenHash = tokenIdToHash[_tokenId];
return tokenHash;
}
/*
___ __ __ ____ ___ ____ _____ __ __ ____ __ ______ ____ ___ ____ _____
/ \ | |__| || \ / _]| \ | || | || \ / ] || |/ \ | \ / ___/
| || | | || _ | / [_ | D ) | __|| | || _ | / /| | | || || _ ( \_
| O || | | || | || _]| / | |_ | | || | |/ / |_| |_| | || O || | |\__ |
| || ` ' || | || [_ | \ | _] | : || | / \_ | | | || || | |/ \ |
| | \ / | | || || . \ | | | || | \ | | | | || || | |\ |
\___/ \_/\_/ |__|__||_____||__|\_| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___|
/**
* @dev Add a trait type
* @param _traitTypeIndex The trait type index
* @param traits Array of traits to add
*/
function addTraitType(uint256 _traitTypeIndex, Trait[] memory traits)
public
onlyOwner
{
for (uint256 i = 0; i < traits.length; i++) {
traitTypes[_traitTypeIndex].push(
Trait(traits[i].traitName, traits[i].traitType)
);
}
return;
}
function flipMintingSwitch() public onlyOwner {
MINTING_LIVE = !MINTING_LIVE;
}
/**
* @dev Sets the p5js url
* @param _p5jsUrl The address of the p5js file hosted on CDN
*/
function setJsAddress(string memory _p5jsUrl) public onlyOwner {
p5jsUrl = _p5jsUrl;
}
/**
* @dev Sets the p5js resource integrity
* @param _p5jsIntegrity The hash of the p5js file (to protect w subresource integrity)
*/
function setJsIntegrity(string memory _p5jsIntegrity) public onlyOwner {
p5jsIntegrity = _p5jsIntegrity;
}
/**
* @dev Sets the base image url
* @param _imageUrl The base url for image field
*/
function setImageUrl(string memory _imageUrl) public onlyOwner {
imageUrl = _imageUrl;
}
function setExternalUrl(string memory _externalUrl) public onlyOwner {
externalUrl = _externalUrl;
}
function withdraw() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{
value: address(this).balance
}("");
require(success);
}
}
|
Generates a 11 digit hash from a tokenId, address, and random number. _t The token id to be used within the hash. _a The address to be used within the hash. _c The custom nonce to be used within the hash./ This will generate a 11 character string. The first 2 digits are the palette.
|
function hash(
uint256 _t,
address _a,
uint256 _c
) internal returns (string memory) {
require(_c < 11);
string memory currentHash = "";
for (uint8 i = 0; i < 6; i++) {
SEED_NONCE++;
uint16 _randinput = uint16(
uint256(
keccak256(
abi.encodePacked(
block.timestamp,
block.difficulty,
_t,
_a,
_c,
SEED_NONCE
)
)
) % 10000
);
currentHash = string(
abi.encodePacked(
currentHash,
rarityGen(_randinput, i).toString()
)
);
}
if (hashToMinted[currentHash]) return hash(_t, _a, _c + 1);
return currentHash;
}
| 12,998,916 |
pragma solidity ^0.4.24;
import "./Strings.sol";
import 'openzeppelin-solidity/contracts/access/Whitelist.sol';
import 'openzeppelin-solidity/contracts/math/SafeMath.sol';
import 'openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol';
/**
* @title InterfaceToken
* https://www.interfacetoken.com/
*/
contract InterfaceToken is ERC721Token, Whitelist {
using SafeMath for uint256;
event Minted(address indexed _owner, uint256 indexed _tokenId, bytes32 _blockhash, bytes32 _nickname);
string internal tokenBaseURI = "https://ipfs.infura.io/ipfs/";
string internal defaultTokenURI = "Qma4QoWXq7YzFUkREXW9wKVYPZmKzS5pkckaSjwY8Gc489";
uint256 public purchaseTokenPointer = 1000000000;
uint256 public costOfToken = 0.01 ether;
mapping(uint256 => bytes32) internal tokenIdToNickname;
mapping(uint256 => bytes32) internal tokenIdToBlockhash;
mapping(bytes32 => uint256) internal blockhashToTokenId;
constructor() public ERC721Token("Interface Token", "TOKN") {
super.addAddressToWhitelist(msg.sender);
}
function() public payable {
buyTokens("");
}
/**
* @dev Mint a new InterfaceToken token
* @dev Reverts if not called by curator
* @param _blockhash an Ethereum block hash
* @param _tokenId unique token ID
* @param _nickname char stamp of token owner
*/
function mint(bytes32 _blockhash, uint256 _tokenId, bytes32 _nickname) external onlyIfWhitelisted(msg.sender) {
require(_tokenId < purchaseTokenPointer); // ensure under number where buying tokens takes place
_mint(_blockhash, _tokenId, _nickname, msg.sender);
}
/**
* @dev Mint a new InterfaceToken token (with recipient)
* @dev Reverts if not called by curator
* @param _blockhash an Ethereum block hash
* @param _tokenId unique token ID
* @param _nickname char stamp of token owner
* @param _recipient owner of the newly minted token
*/
function mintTransfer(bytes32 _blockhash, uint256 _tokenId, bytes32 _nickname, address _recipient) external onlyIfWhitelisted(msg.sender) {
require(_tokenId < purchaseTokenPointer); // ensure under number where buying tokens takes place
_mint(_blockhash, _tokenId, _nickname, _recipient);
}
/**
* @dev Purchases a new InterfaceToken token
* @dev Reverts if not called by curator
* @param _nickname char stamp of token owner
*/
function buyToken(bytes32 _nickname) public payable {
require(msg.value >= costOfToken);
_mint(keccak256(abi.encodePacked(purchaseTokenPointer, _nickname)), purchaseTokenPointer, _nickname, msg.sender);
purchaseTokenPointer = purchaseTokenPointer.add(1);
// reconcile payments
owner.transfer(costOfToken);
msg.sender.transfer(msg.value - costOfToken);
}
/**
* @dev Purchases multiple new InterfaceToken tokens
* @dev Reverts if not called by curator
* @param _nickname char stamp of token owner
*/
function buyTokens(bytes32 _nickname) public payable {
require(msg.value >= costOfToken);
uint i = 0;
for (i; i < (msg.value / costOfToken); i++) {
_mint(keccak256(abi.encodePacked(purchaseTokenPointer, _nickname)), purchaseTokenPointer, _nickname, msg.sender);
purchaseTokenPointer = purchaseTokenPointer.add(1);
}
// reconcile payments
owner.transfer(costOfToken * i);
msg.sender.transfer(msg.value - (costOfToken * i));
}
function _mint(bytes32 _blockhash, uint256 _tokenId, bytes32 _nickname, address _recipient) internal {
require(_recipient != address(0));
require(blockhashToTokenId[_blockhash] == 0);
require(tokenIdToBlockhash[_tokenId] == 0);
// mint the token with sender as owner
super._mint(_recipient, _tokenId);
// set data
tokenIdToBlockhash[_tokenId] = _blockhash;
blockhashToTokenId[_blockhash] = _tokenId;
tokenIdToNickname[_tokenId] = _nickname;
emit Minted(_recipient, _tokenId, _blockhash, _nickname);
}
/**
* @dev Utility function changing the cost of the token
* @dev Reverts if not called by owner
* @param _costOfToken cost in wei
*/
function setCostOfToken(uint256 _costOfToken) external onlyIfWhitelisted(msg.sender) {
costOfToken = _costOfToken;
}
/**
* @dev Utility function for updating a nickname if you own the token
* @dev Reverts if not called by owner
* @param _tokenId the token ID
* @param _nickname char stamp of token owner
*/
function setNickname(uint256 _tokenId, bytes32 _nickname) external onlyOwnerOf(_tokenId) {
tokenIdToNickname[_tokenId] = _nickname;
}
/**
* @dev Return owned tokens
* @param _owner address to query
*/
function tokensOf(address _owner) public view returns (uint256[] _tokenIds) {
return ownedTokens[_owner];
}
/**
* @dev checks for owned tokens
* @param _owner address to query
*/
function hasTokens(address _owner) public view returns (bool) {
return ownedTokens[_owner].length > 0;
}
/**
* @dev checks for owned tokens
* @param _owner address to query
*/
function firstToken(address _owner) public view returns (uint256 _tokenId) {
require(hasTokens(_owner));
return ownedTokens[_owner][0];
}
/**
* @dev Return handle of token
* @param _tokenId token ID for handle lookup
*/
function nicknameOf(uint256 _tokenId) public view returns (bytes32 _nickname) {
return tokenIdToNickname[_tokenId];
}
/**
* @dev Get token URI fro the given token, useful for testing purposes
* @param _tokenId the token ID
* @return the token ID or only the base URI if not found
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
if (bytes(tokenURIs[_tokenId]).length == 0) {
return Strings.strConcat(tokenBaseURI, defaultTokenURI);
}
return Strings.strConcat(tokenBaseURI, tokenURIs[_tokenId]);
}
/**
* @dev Allows management to update the base tokenURI path
* @dev Reverts if not called by owner
* @param _newBaseURI the new base URI to set
*/
function setTokenBaseURI(string _newBaseURI) external onlyOwner {
tokenBaseURI = _newBaseURI;
}
/**
* @dev Allows management to update the default token URI
* @dev Reverts if not called by owner
* @param _defaultTokenURI the new default URI to set
*/
function setDefaultTokenURI(string _defaultTokenURI) external onlyOwner {
defaultTokenURI = _defaultTokenURI;
}
/**
* @dev Utility function for updating an assets token URI
* @dev Reverts if not called by management
* @param _tokenId the token ID
* @param _uri the token URI, will be concatenated with baseUri
*/
function setTokenURI(uint256 _tokenId, string _uri) external onlyIfWhitelisted(msg.sender) {
require(exists(_tokenId));
_setTokenURI(_tokenId, _uri);
}
/**
* @dev Return blockhash of the token
* @param _tokenId the token ID
*/
function blockhashOf(uint256 _tokenId) public view returns (bytes32 hash) {
return tokenIdToBlockhash[_tokenId];
}
/**
* @dev Return token ID of a Blockhash
* @param _blockhash blockhash reference
*/
function tokenIdOf(bytes32 _blockhash) public view returns (uint256 hash) {
return blockhashToTokenId[_blockhash];
}
/**
* @dev Return blockhash of the token
* @param _tokenId the token ID
*/
function burn(uint256 _tokenId) public {
super._burn(msg.sender, _tokenId);
bytes32 tokenBlockhash = tokenIdToBlockhash[_tokenId];
if (tokenIdToBlockhash[_tokenId].length != 0) {
delete tokenIdToBlockhash[_tokenId];
}
if (tokenIdToNickname[_tokenId].length != 0) {
delete tokenIdToNickname[_tokenId];
}
if (blockhashToTokenId[tokenBlockhash] != 0) {
delete blockhashToTokenId[tokenBlockhash];
}
}
}
|
checks for owned tokens _owner address to query/
|
function hasTokens(address _owner) public view returns (bool) {
return ownedTokens[_owner].length > 0;
}
| 6,452,192 |
pragma solidity ^0.4.18;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
function DetailedERC20(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
/**
* Crowdsale has a life span during which investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to beneficiary
* as they arrive.
*
* A crowdsale is defined by:
* offset (required) - crowdsale start, unix timestamp
* length (required) - crowdsale length in seconds
* price (required) - token price in wei
* soft cap (optional) - minimum amount of funds required for crowdsale success, can be zero (if not used)
* hard cap (optional) - maximum amount of funds crowdsale can accept, can be zero (unlimited)
* quantum (optional) - enables value accumulation effect to reduce value transfer costs, usually is not used (set to zero)
* if non-zero value passed specifies minimum amount of wei to transfer to beneficiary
*
* This crowdsale doesn't own tokens and doesn't perform any token emission.
* It expects enough tokens to be available on its address:
* these tokens are used for issuing them to investors.
* Token redemption is done in opposite way: tokens accumulate back on contract's address
* Beneficiary is specified by its address.
* This implementation can be used to make several crowdsales with the same token being sold.
*/
contract Crowdsale {
/**
* Descriptive name of this Crowdsale. There could be multiple crowdsales for same Token.
*/
string public name;
// contract creator, owner of the contract
// creator is also supplier of tokens
address private creator;
// crowdsale start (unix timestamp)
uint public offset;
// crowdsale length in seconds
uint public length;
// one token price in wei
uint public price;
// crowdsale minimum goal in wei
uint public softCap;
// crowdsale maximum goal in wei
uint public hardCap;
// minimum amount of value to transfer to beneficiary in automatic mode
uint private quantum;
// how much value collected (funds raised)
uint public collected;
// how many different addresses made an investment
uint public investorsCount;
// how much value refunded (if crowdsale failed)
uint public refunded;
// how much tokens issued to investors
uint public tokensIssued;
// how much tokens redeemed and refunded (if crowdsale failed)
uint public tokensRedeemed;
// how many successful transactions (with tokens being send back) do we have
uint public transactions;
// how many refund transactions (in exchange for tokens) made (if crowdsale failed)
uint public refunds;
// The token being sold
DetailedERC20 private token;
// decimal coefficient (k) enables support for tokens with non-zero decimals
uint k;
// address where funds are collected
address public beneficiary;
// investor's mapping, required for token redemption in a failed crowdsale
// making this field public allows to extend investor-related functionality in the future
mapping(address => uint) public balances;
// events to log
event InvestmentAccepted(address indexed holder, uint tokens, uint value);
event RefundIssued(address indexed holder, uint tokens, uint value);
// a crowdsale is defined by a set of parameters passed here
// make sure _end timestamp is in the future in order for crowdsale to be operational
// _price must be positive, this is a price of one token in wei
// _hardCap must be greater then _softCap or zero, zero _hardCap means unlimited crowdsale
// _quantum may be zero, in this case there will be no value accumulation on the contract
function Crowdsale(
string _name,
uint _offset,
uint _length,
uint _price,
uint _softCap,
uint _hardCap,
uint _quantum,
address _beneficiary,
address _token
) public {
// validate crowdsale settings (inputs)
// require(_offset > 0); // we don't really care
require(_length > 0);
require(now < _offset + _length); // crowdsale must not be already finished
// softCap can be anything, zero means crowdsale doesn't fail
require(_hardCap > _softCap || _hardCap == 0);
// hardCap must be greater then softCap
// quantum can be anything, zero means no accumulation
require(_price > 0);
require(_beneficiary != address(0));
require(_token != address(0));
name = _name;
// setup crowdsale settings
offset = _offset;
length = _length;
softCap = _softCap;
hardCap = _hardCap;
quantum = _quantum;
price = _price;
creator = msg.sender;
// define beneficiary
beneficiary = _beneficiary;
// allocate tokens: link and init coefficient
__allocateTokens(_token);
}
// accepts crowdsale investment, requires
// crowdsale to be running and not reached its goal
function invest() public payable {
// perform validations
assert(now >= offset && now < offset + length); // crowdsale is active
assert(collected + price <= hardCap || hardCap == 0); // its still possible to buy at least 1 token
require(msg.value >= price); // value sent is enough to buy at least one token
// call 'sender' nicely - investor
address investor = msg.sender;
// how much tokens we must send to investor
uint tokens = msg.value / price;
// how much value we must send to beneficiary
uint value = tokens * price;
// ensure we are not crossing the hardCap
if (value + collected > hardCap || hardCap == 0) {
value = hardCap - collected;
tokens = value / price;
value = tokens * price;
}
// update crowdsale status
collected += value;
tokensIssued += tokens;
// transfer tokens to investor
__issueTokens(investor, tokens);
// transfer the change to investor
investor.transfer(msg.value - value);
// accumulate the value or transfer it to beneficiary
if (collected >= softCap && this.balance >= quantum) {
// transfer all the value to beneficiary
__beneficiaryTransfer(this.balance);
}
// log an event
InvestmentAccepted(investor, tokens, value);
}
// refunds an investor of failed crowdsale,
// requires investor to allow token transfer back
function refund() public payable {
// perform validations
assert(now >= offset + length); // crowdsale ended
assert(collected < softCap); // crowdsale failed
// call 'sender' nicely - investor
address investor = msg.sender;
// find out how much tokens should be refunded
uint tokens = __redeemAmount(investor);
// calculate refund amount
uint refundValue = tokens * price;
// additional validations
require(tokens > 0);
// update crowdsale status
refunded += refundValue;
tokensRedeemed += tokens;
refunds++;
// transfer the tokens back
__redeemTokens(investor, tokens);
// make a refund
investor.transfer(refundValue + msg.value);
// log an event
RefundIssued(investor, tokens, refundValue);
}
// sends all the value to the beneficiary
function withdraw() public {
// perform validations
assert(creator == msg.sender || beneficiary == msg.sender); // only creator or beneficiary can initiate this call
assert(collected >= softCap); // crowdsale must be successful
assert(this.balance > 0); // there should be something to transfer
// how much to withdraw (entire balance obviously)
uint value = this.balance;
// perform the transfer
__beneficiaryTransfer(value);
}
// performs an investment, refund or withdrawal,
// depending on the crowdsale status
function() public payable {
// started or finished
require(now >= offset);
if(now < offset + length) {
// crowdsale is running, invest
invest();
}
else if(collected < softCap) {
// crowdsale failed, try to refund
refund();
}
else {
// crowdsale is successful, investments are not accepted anymore
// but maybe poor beneficiary is begging for change...
withdraw();
}
}
// ----------------------- internal section -----------------------
// allocates token source (basically links token)
function __allocateTokens(address _token) internal {
// link tokens, tokens are not owned by a crowdsale
// should be transferred to crowdsale after the deployment
token = DetailedERC20(_token);
// obtain decimals and calculate coefficient k
k = 10 ** uint(token.decimals());
}
// transfers tokens to investor, validations are not required
function __issueTokens(address investor, uint tokens) internal {
// if this is a new investor update investor count
if (balances[investor] == 0) {
investorsCount++;
}
// for open crowdsales we track investors balances
balances[investor] += tokens;
// issue tokens, taking into account decimals
token.transferFrom(creator, investor, tokens * k);
}
// calculates amount of tokens available to redeem from investor, validations are not required
function __redeemAmount(address investor) internal view returns (uint amount) {
// round down allowance taking into account token decimals
uint allowance = token.allowance(investor, this) / k;
// for open crowdsales we check previously tracked investor balance
uint balance = balances[investor];
// return allowance safely by checking also the balance
return balance < allowance ? balance : allowance;
}
// transfers tokens from investor, validations are not required
function __redeemTokens(address investor, uint tokens) internal {
// for open crowdsales we track investors balances
balances[investor] -= tokens;
// redeem tokens, taking into account decimals coefficient
token.transferFrom(investor, creator, tokens * k);
}
// transfers a value to beneficiary, validations are not required
function __beneficiaryTransfer(uint value) internal {
beneficiary.transfer(value);
}
// !---------------------- internal section ----------------------!
}
|
sends all the value to the beneficiary perform validations how much to withdraw (entire balance obviously) perform the transfer
|
function withdraw() public {
uint value = this.balance;
__beneficiaryTransfer(value);
}
| 6,677,680 |
pragma solidity 0.5.16;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "./interfaces/IIdleTokenV3_1.sol";
import "./interfaces/IIdleToken.sol";
import "./others/BasicMetaTransaction.sol";
/* import "./others/EIP712MetaTransaction.sol"; */
import "./GST2Consumer.sol";
interface CERC20 {
function redeem(uint256 redeemTokens) external returns (uint256);
}
interface AToken {
function redeem(uint256 amount) external;
}
interface iERC20Fulcrum {
function burn(
address receiver,
uint256 burnAmount)
external
returns (uint256 loanAmountPaid);
}
interface yToken {
function withdraw(uint256 _shares) external;
}
// This contract should never have tokens at the end of a transaction.
// if for some reason tokens are stuck inside there is an emergency withdraw method
// This contract is not audited
contract IdleConverterPersonalSignV4 is Ownable, GST2Consumer, BasicMetaTransaction {
using SafeERC20 for IERC20;
using SafeMath for uint256;
constructor() public {}
// One should approve this contract first to spend IdleTokens
// _amount : in oldIdleTokens
// _from : old idle address
// _to : new idle address
// _underlying : underlying addr intially redeemd (eg. DAI)
function migrateFromToIdle(uint256 _amount, address _from, address _to, address _underlying, bool _skipRebalance) external gasDiscountFrom(address(this)) returns (uint256) {
IERC20(_from).safeTransferFrom(msgSender(), address(this), _amount);
IIdleToken(_from).redeemIdleToken(_amount, true, new uint256[](0));
return _migrateToIdle(_to, _underlying, _skipRebalance);
}
// One should approve this contract first to spend cTokens
// _amount : in cTokens
// _from : old idle address
// _to : new idle address
// _underlying : underlying addr intially redeemd (eg. DAI)
function migrateFromCompoundToIdle(uint256 _amount, address _from, address _to, address _underlying, bool _skipRebalance) external gasDiscountFrom(address(this)) returns (uint256) {
IERC20(_from).safeTransferFrom(msgSender(), address(this), _amount);
CERC20(_from).redeem(_amount);
return _migrateToIdle(_to, _underlying, _skipRebalance);
}
// One should approve this contract first to spend iTokens
// _amount : in iTokens
// _from : old idle address
// _to : new idle address
// _underlying : underlying addr intially redeemd (eg. DAI)
function migrateFromFulcrumToIdle(uint256 _amount, address _from, address _to, address _underlying, bool _skipRebalance) external gasDiscountFrom(address(this)) returns (uint256) {
IERC20(_from).safeTransferFrom(msgSender(), address(this), _amount);
iERC20Fulcrum(_from).burn(address(this), _amount);
return _migrateToIdle(_to, _underlying, _skipRebalance);
}
// One should approve this contract first to spend aTokens
// _amount : in aTokens
// _from : old idle address
// _to : new idle address
// _underlying : underlying addr intially redeemd (eg. DAI)
function migrateFromAaveToIdle(uint256 _amount, address _from, address _to, address _underlying, bool _skipRebalance) external gasDiscountFrom(address(this)) returns (uint256) {
IERC20(_from).safeTransferFrom(msgSender(), address(this), _amount);
AToken(_from).redeem(_amount);
return _migrateToIdle(_to, _underlying, _skipRebalance);
}
// One should approve this contract first to spend yTokens
// _amount : in yTokens
// _from : old idle address
// _to : new idle address
// _underlying : underlying addr intially redeemd (eg. DAI)
function migrateFromIearnToIdle(uint256 _amount, address _from, address _to, address _underlying, bool _skipRebalance) external gasDiscountFrom(address(this)) returns (uint256) {
IERC20(_from).safeTransferFrom(msgSender(), address(this), _amount);
yToken(_from).withdraw(_amount);
return _migrateToIdle(_to, _underlying, _skipRebalance);
}
// internal
// _to : new idle address
// _underlying : underlying addr intially redeemd (eg. DAI)
function _migrateToIdle(address _to, address _underlying, bool _skipRebalance) internal returns (uint256 newIdleTokens) {
uint256 underlyingBalance = IERC20(_underlying).balanceOf(address(this));
IERC20(_underlying).safeApprove(_to, underlyingBalance);
IIdleTokenV3_1(_to).mintIdleToken(underlyingBalance, _skipRebalance, address(0));
newIdleTokens = IERC20(_to).balanceOf(address(this));
IERC20(_to).safeTransfer(msgSender(), newIdleTokens);
}
// onlyOwner
function emergencyWithdrawToken(address _token, address _to) external onlyOwner {
IERC20(_token).safeTransfer(_to, IERC20(_token).balanceOf(address(this)));
}
}
|
internal _to : new idle address _underlying : underlying addr intially redeemd (eg. DAI)
|
function _migrateToIdle(address _to, address _underlying, bool _skipRebalance) internal returns (uint256 newIdleTokens) {
uint256 underlyingBalance = IERC20(_underlying).balanceOf(address(this));
IERC20(_underlying).safeApprove(_to, underlyingBalance);
IIdleTokenV3_1(_to).mintIdleToken(underlyingBalance, _skipRebalance, address(0));
newIdleTokens = IERC20(_to).balanceOf(address(this));
IERC20(_to).safeTransfer(msgSender(), newIdleTokens);
}
| 6,431,320 |
./full_match/5/0x40a14bb4c7f4b6a6083cf2a6686daAd3cd3aF60E/sources/contracts/Contract.sol
|
Player joins battle
|
function joinBattle(string memory _name, uint256 _betAmount, NFTInfo memory _nftInfo) external nonReentrant returns (Battle memory) {
Battle memory _battle = getBattle(_name);
require(_battle.betAmount[0] == _betAmount, "Insufficient bet amount !");
_receiveBattleReward(_battle.token, _betAmount);
_battle.battleStatus = BattleStatus.STARTED;
_battle.betReward = PureFunction.sumRewards([_battle.betAmount[0], _betAmount]);
_battle.players[1] = msg.sender;
_battle.betAmount[1] = _betAmount;
_battle.tokenIdNFT[1] = _nftInfo.tokenId;
_battle.rarityIdNFT[1] = _nftInfo.rarity;
_battle.turnTime[1] = block.timestamp;
_battle.turnTime[0] = block.timestamp;
_battle.battleStartTime = block.timestamp;
updateBattle(_name, _battle);
_updatePlayerTokenStrength(msg.sender, [PureFunction.calculateAttackStrength(_nftInfo.rarity), PureFunction.calculateDefenseStrength(_nftInfo.rarity)]);
players[playerInfo[_battle.players[0]]].inBattle = true;
players[playerInfo[_battle.players[1]]].inBattle = true;
return _battle;
}
| 1,907,530 |
./partial_match/3/0xCD58F9cdc9f8955a36bF14Cc76B59F840FFe914e/sources/BRDSupplier.sol
|
Interface of the ERC20 standard as defined in the EIP./
|
interface IERC20 {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
| 5,101,595 |
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// token contract interface
interface Token{
function balanceOf(address user) external returns(uint256);
function transfer(address to, uint256 amount) external returns(bool);
}
contract Safe{
using SafeMath for uint256;
// counter for signing transactions
uint8 public count;
uint256 internal end;
uint256 internal timeOutAuthentication;
// arrays of safe keys
mapping (address => bool) internal safeKeys;
address [] internal massSafeKeys = new address[](4);
// array of keys that signed the transaction
mapping (address => bool) internal signKeys;
// free amount in safe
uint256 internal freeAmount;
// event transferring money to safe
bool internal tranche;
// fixing lockup in safe
bool internal lockupIsSet;
// lockup of safe
uint256 internal mainLockup;
address internal lastSafeKey;
Token public token;
// Amount of cells
uint256 public countOfCell;
// cell structure
struct _Cell{
uint256 lockup;
uint256 balance;
bool exist;
uint256 timeOfDeposit;
}
// cell addresses
mapping (address => _Cell) internal userCells;
event CreateCell(address indexed key);
event Deposit(address indexed key, uint256 balance);
event Delete(address indexed key);
event Edit(address indexed key, uint256 lockup);
event Withdraw(address indexed who, uint256 balance);
event InternalTransfer(address indexed from, address indexed to, uint256 balance);
modifier firstLevel() {
require(msg.sender == lastSafeKey);
require(count>=1);
require(now < end);
_;
}
modifier secondLevel() {
require(msg.sender == lastSafeKey);
require(count>=2);
require(now < end);
_;
}
modifier thirdLevel() {
require(msg.sender == lastSafeKey);
require(count>=3);
require(now < end);
_;
}
constructor (address _first, address _second, address _third, address _fourth) public {
require(
_first != _second &&
_first != _third &&
_first != _fourth &&
_second != _third &&
_second != _fourth &&
_third != _fourth &&
_first != 0x0 &&
_second != 0x0 &&
_third != 0x0 &&
_fourth != 0x0
);
safeKeys[_first] = true;
safeKeys[_second] = true;
safeKeys[_third] = true;
safeKeys[_fourth] = true;
massSafeKeys[0] = _first;
massSafeKeys[1] = _second;
massSafeKeys[2] = _third;
massSafeKeys[3] = _fourth;
timeOutAuthentication = 1 hours;
}
function AuthStart() public returns(bool){
require(safeKeys[msg.sender]);
require(timeOutAuthentication >=0);
require(!signKeys[msg.sender]);
signKeys[msg.sender] = true;
count++;
end = now.add(timeOutAuthentication);
lastSafeKey = msg.sender;
return true;
}
// completion of operation with safe-keys
function AuthEnd() public returns(bool){
require (safeKeys[msg.sender]);
for(uint i=0; i<4; i++){
signKeys[massSafeKeys[i]] = false;
}
count = 0;
end = 0;
lastSafeKey = 0x0;
return true;
}
function getTimeOutAuthentication() firstLevel public view returns(uint256){
return timeOutAuthentication;
}
function getFreeAmount() firstLevel public view returns(uint256){
return freeAmount;
}
function getLockupCell(address _user) firstLevel public view returns(uint256){
return userCells[_user].lockup;
}
function getBalanceCell(address _user) firstLevel public view returns(uint256){
return userCells[_user].balance;
}
function getExistCell(address _user) firstLevel public view returns(bool){
return userCells[_user].exist;
}
function getSafeKey(uint i) firstLevel view public returns(address){
return massSafeKeys[i];
}
// withdrawal tokens from safe for issuer
function AssetWithdraw(address _to, uint256 _balance) secondLevel public returns(bool){
require(_balance<=freeAmount);
require(now>=mainLockup);
freeAmount = freeAmount.sub(_balance);
token.transfer(_to, _balance);
emit Withdraw(this, _balance);
return true;
}
function setCell(address _cell, uint256 _lockup) secondLevel public returns(bool){
require(userCells[_cell].lockup==0 && userCells[_cell].balance==0);
require(!userCells[_cell].exist);
require(_lockup >= mainLockup);
userCells[_cell].lockup = _lockup;
userCells[_cell].exist = true;
countOfCell = countOfCell.add(1);
emit CreateCell(_cell);
return true;
}
function deleteCell(address _key) secondLevel public returns(bool){
require(getBalanceCell(_key)==0);
require(userCells[_key].exist);
userCells[_key].lockup = 0;
userCells[_key].exist = false;
countOfCell = countOfCell.sub(1);
emit Delete(_key);
return true;
}
// change parameters of the cell
function editCell(address _key, uint256 _lockup) secondLevel public returns(bool){
require(getBalanceCell(_key)==0);
require(_lockup>= mainLockup);
require(userCells[_key].exist);
userCells[_key].lockup = _lockup;
emit Edit(_key, _lockup);
return true;
}
function depositCell(address _key, uint256 _balance) secondLevel public returns(bool){
require(userCells[_key].exist);
require(_balance<=freeAmount);
freeAmount = freeAmount.sub(_balance);
userCells[_key].balance = userCells[_key].balance.add(_balance);
userCells[_key].timeOfDeposit = now;
emit Deposit(_key, _balance);
return true;
}
function changeDepositCell(address _key, uint256 _balance) secondLevel public returns(bool){
require(userCells[_key].timeOfDeposit.add(1 hours)>now);
userCells[_key].balance = userCells[_key].balance.sub(_balance);
freeAmount = freeAmount.add(_balance);
return true;
}
// installation of a lockup for safe,
// fixing free amount on balance,
// token installation
// (run once)
function setContract(Token _token, uint256 _lockup) thirdLevel public returns(bool){
require(_token != address(0x0));
require(!lockupIsSet);
require(!tranche);
token = _token;
freeAmount = getMainBalance();
mainLockup = _lockup;
tranche = true;
lockupIsSet = true;
return true;
}
// change of safe-key
function changeKey(address _oldKey, address _newKey) thirdLevel public returns(bool){
require(safeKeys[_oldKey]);
require(_newKey != 0x0);
for(uint i=0; i<4; i++){
if(massSafeKeys[i]==_oldKey){
massSafeKeys[i] = _newKey;
}
}
safeKeys[_oldKey] = false;
safeKeys[_newKey] = true;
if(_oldKey==lastSafeKey){
lastSafeKey = _newKey;
}
return true;
}
function setTimeOutAuthentication(uint256 _time) thirdLevel public returns(bool){
require(
_time > 0 &&
timeOutAuthentication != _time &&
_time <= (5000 * 1 minutes)
);
timeOutAuthentication = _time;
return true;
}
function withdrawCell(uint256 _balance) public returns(bool){
require(userCells[msg.sender].balance >= _balance);
require(now >= userCells[msg.sender].lockup);
userCells[msg.sender].balance = userCells[msg.sender].balance.sub(_balance);
token.transfer(msg.sender, _balance);
emit Withdraw(msg.sender, _balance);
return true;
}
// transferring tokens from one cell to another
function transferCell(address _to, uint256 _balance) public returns(bool){
require(userCells[msg.sender].balance >= _balance);
require(userCells[_to].lockup>=userCells[msg.sender].lockup);
require(userCells[_to].exist);
userCells[msg.sender].balance = userCells[msg.sender].balance.sub(_balance);
userCells[_to].balance = userCells[_to].balance.add(_balance);
emit InternalTransfer(msg.sender, _to, _balance);
return true;
}
// information on balance of cell for holder
function getInfoCellBalance() view public returns(uint256){
return userCells[msg.sender].balance;
}
// information on lockup of cell for holder
function getInfoCellLockup() view public returns(uint256){
return userCells[msg.sender].lockup;
}
function getMainBalance() public view returns(uint256){
return token.balanceOf(this);
}
function getMainLockup() public view returns(uint256){
return mainLockup;
}
function isTimeOver() view public returns(bool){
if(now > end){
return true;
} else{
return false;
}
}
}
|
token contract interface
|
interface Token{
function balanceOf(address user) external returns(uint256);
function transfer(address to, uint256 amount) external returns(bool);
}
| 6,727,642 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { ERC721 } from "./ERC721/ERC721.sol";
import { ERC721M } from "./ERC721/ERC721M.sol";
import { ERC721Tradable } from "./ERC721/extensions/ERC721Tradable.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
contract Mingoes is ERC721M, ERC721Tradable, Ownable {
uint256 public constant PRICE = 0.04 ether;
uint256 public constant MAX_SUPPLY = 10000;
uint256 public constant MAX_RESERVE = 300;
uint256 public constant MAX_PUBLIC = 9700; // MAX_SUPPLY - MAX_RESERVE
uint256 public constant MAX_FREE = 200;
uint256 public constant MAX_TX = 20;
uint256 public reservesMinted;
string public baseURI;
bool public isSaleActive;
mapping (address => bool) public hasClaimed;
/* -------------------------------------------------------------------------- */
/* CONSTRUCTOR */
/* -------------------------------------------------------------------------- */
constructor(
address _openSeaProxyRegistry,
address _looksRareTransferManager,
string memory _baseURI
) payable ERC721M("Mingoes", "MINGOES") ERC721Tradable(_openSeaProxyRegistry, _looksRareTransferManager) {
baseURI = _baseURI;
}
/* -------------------------------------------------------------------------- */
/* USER */
/* -------------------------------------------------------------------------- */
/// @notice Mints an amount of tokens and transfers them to the caller during the public sale.
/// @param amount The amount of tokens to mint.
function publicMint(uint256 amount) external payable {
require(isSaleActive, "Sale is not active");
require(msg.sender == tx.origin, "No contracts allowed");
uint256 _totalSupply = totalSupply();
if (_totalSupply < MAX_FREE) {
require(!hasClaimed[msg.sender], "Already claimed");
hasClaimed[msg.sender] = true;
_mint(msg.sender, 1);
return;
}
require(msg.value == PRICE * amount, "Wrong ether amount");
require(amount <= MAX_TX, "Amount exceeds tx limit");
require(_totalSupply + amount <= MAX_PUBLIC, "Max public supply reached");
_mint(msg.sender, amount);
}
/* -------------------------------------------------------------------------- */
/* OWNER */
/* -------------------------------------------------------------------------- */
/// @notice Enables or disables minting through {publicMint}.
/// @dev Requirements:
/// - Caller must be the owner.
function setIsSaleActive(bool _isSaleActive) external onlyOwner {
isSaleActive = _isSaleActive;
}
/// @notice Mints tokens to multiple addresses.
/// @dev Requirements:
/// - Caller must be the owner.
/// @param recipients The addresses to mint the tokens to.
/// @param amounts The amounts of tokens to mint.
function reserveMint(address[] calldata recipients, uint256[] calldata amounts) external onlyOwner {
unchecked {
uint256 sum;
uint256 length = recipients.length;
for (uint256 i; i < length; i++) {
address to = recipients[i];
require(to != address(0), "Invalid recipient");
uint256 amount = amounts[i];
_mint(to, amount);
sum += amount;
}
uint256 totalReserves = reservesMinted + sum;
require(totalSupply() <= MAX_SUPPLY, "Max supply reached");
require(totalReserves <= MAX_RESERVE, "Amount exceeds reserve limit");
reservesMinted = totalReserves;
}
}
/// @notice Sets the base Uniform Resource Identifier (URI) for token metadata.
/// @dev Requirements:
/// - Caller must be the owner.
/// @param _baseURI The base URI.
function setBaseURI(string calldata _baseURI) external onlyOwner {
baseURI = _baseURI;
}
/// @notice Withdraws all contract balance to the caller.
/// @dev Requirements:
/// - Caller must be the owner.
function withdrawETH() external onlyOwner {
_transferETH(msg.sender, address(this).balance);
}
/// @dev Requirements:
/// - Caller must be the owner.
/// @inheritdoc ERC721Tradable
function setMarketplaceApprovalForAll(bool approved) public override onlyOwner {
marketPlaceApprovalForAll = approved;
}
/* -------------------------------------------------------------------------- */
/* SOLIDITY OVERRIDES */
/* -------------------------------------------------------------------------- */
/// @inheritdoc ERC721
function tokenURI(uint256 id) public view override returns (string memory) {
require(_exists(id), "NONEXISTENT_TOKEN");
string memory _baseURI = baseURI;
return bytes(_baseURI).length == 0 ? "" : string(abi.encodePacked(_baseURI, toString(id)));
}
/// @inheritdoc ERC721Tradable
function isApprovedForAll(address owner, address operator) public view override(ERC721, ERC721Tradable) returns (bool) {
return ERC721Tradable.isApprovedForAll(owner, operator);
}
/* -------------------------------------------------------------------------- */
/* UTILS */
/* -------------------------------------------------------------------------- */
function _transferETH(address to, uint256 value) internal {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = to.call{ value: value }("");
require(success, "ETH transfer failed");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { ERC721TokenReceiver } from "./ERC721TokenReceiver.sol";
abstract contract ERC721 {
/* -------------------------------------------------------------------------- */
/* EVENTS */
/* -------------------------------------------------------------------------- */
/// @dev Emitted when `id` token is transferred from `from` to `to`.
event Transfer(address indexed from, address indexed to, uint256 indexed id);
/// @dev Emitted when `owner` enables `approved` to manage the `id` token.
event Approval(address indexed owner, address indexed spender, uint256 indexed id);
/// @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/* -------------------------------------------------------------------------- */
/* METADATA STORAGE */
/* -------------------------------------------------------------------------- */
/// @dev The collection name.
string private _name;
/// @dev The collection symbol.
string private _symbol;
/* -------------------------------------------------------------------------- */
/* ERC721 STORAGE */
/* -------------------------------------------------------------------------- */
/// @dev ID => spender
mapping(uint256 => address) internal _tokenApprovals;
/// @dev owner => operator => approved
mapping(address => mapping(address => bool)) internal _operatorApprovals;
/* -------------------------------------------------------------------------- */
/* CONSTRUCTOR */
/* -------------------------------------------------------------------------- */
/// @param name_ The collection name.
/// @param symbol_ The collection symbol.
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/* -------------------------------------------------------------------------- */
/* ERC165 LOGIC */
/* -------------------------------------------------------------------------- */
/// @notice Returns true if this contract implements an interface from its ID.
/// @dev See the corresponding
/// [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
/// to learn more about how these IDs are created.
/// @return The implementation status.
function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) {
return
interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165
interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721
interfaceId == 0x5b5e139f || // ERC165 Interface ID for ERC721Metadata
interfaceId == 0x780e9d63; // ERC165 Interface ID for ERC721Enumerable
}
/* -------------------------------------------------------------------------- */
/* METADATA LOGIC */
/* -------------------------------------------------------------------------- */
/// @notice Returns the collection name.
/// @return The collection name.
function name() public view virtual returns (string memory) {
return _name;
}
/// @notice Returns the collection symbol.
/// @return The collection symbol.
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/// @notice Returns the Uniform Resource Identifier (URI) for `id` token.
/// @param id The token ID.
/// @return The URI.
function tokenURI(uint256 id) public view virtual returns (string memory);
/* -------------------------------------------------------------------------- */
/* ENUMERABLE LOGIC */
/* -------------------------------------------------------------------------- */
/// @notice Returns the total amount of tokens stored by the contract.
/// @return The token supply.
function totalSupply() public view virtual returns (uint256);
/// @notice Returns a token ID owned by `owner` at a given `index` of its token list.
/// @dev Use along with {balanceOf} to enumerate all of `owner`'s tokens.
/// @param owner The address to query.
/// @param index The index to query.
/// @return The token ID.
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256);
/// @notice Returns a token ID at a given `index` of all the tokens stored by the contract.
/// @dev Use along with {totalSupply} to enumerate all tokens.
/// @param index The index to query.
/// @return The token ID.
function tokenByIndex(uint256 index) public view virtual returns (uint256);
/* -------------------------------------------------------------------------- */
/* ERC721 LOGIC */
/* -------------------------------------------------------------------------- */
/// @notice Returns the account approved for a token ID.
/// @dev Requirements:
/// - `id` must exist.
/// @param id Token ID to query.
/// @return The account approved for `id` token.
function getApproved(uint256 id) public virtual returns (address) {
require(_exists(id), "NONEXISTENT_TOKEN");
return _tokenApprovals[id];
}
/// @notice Returns if the `operator` is allowed to manage all of the assets of `owner`.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return True if `operator` was approved by `owner`.
function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {
return _operatorApprovals[owner][operator];
}
/// @notice Gives permission to `to` to transfer `id` token to another account.
/// @dev The approval is cleared when the token is transferred.
/// Only a single account can be approved at a time, so approving the zero address clears previous approvals.
/// Requirements:
/// - The caller must own the token or be an approved operator.
/// - `id` must exist.
/// Emits an {Approval} event.
/// @param spender The address of the spender to approve to.
/// @param id The token ID to approve.
function approve(address spender, uint256 id) public virtual {
address owner = ownerOf(id);
require(isApprovedForAll(owner, msg.sender) || msg.sender == owner, "NOT_AUTHORIZED");
_tokenApprovals[id] = spender;
emit Approval(owner, spender, id);
}
/// @notice Approve or remove `operator` as an operator for the caller.
/// @dev Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
/// Emits an {ApprovalForAll} event.
/// @param operator The address of the operator to approve.
/// @param approved The status to set.
function setApprovalForAll(address operator, bool approved) public virtual {
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
/// @notice Transfers `id` token from `from` to `to`.
/// WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
/// @dev Requirements:
/// - `to` cannot be the zero address.
/// - `id` token must be owned by `from`.
/// - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
/// Emits a {Transfer} event.
/// @param from The address to transfer from.
/// @param to The address to transfer to.
/// @param id The token ID to transfer.
function transferFrom(
address from,
address to,
uint256 id
) public virtual {
_transfer(from, to, id);
}
/// @notice Safely transfers `id` token from `from` to `to`.
/// @dev Requirements:
/// - `to` cannot be the zero address.
/// - `id` token must exist and be owned by `from`.
/// - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
/// - If `to` refers to a smart contract, it must implement {ERC721TokenReceiver-onERC721Received}, which is called upon a safe transfer.
/// Emits a {Transfer} event.
/// @param from The address to transfer from.
/// @param to The address to transfer to.
/// @param id The token ID to transfer.
function safeTransferFrom(
address from,
address to,
uint256 id
) public virtual {
_transfer(from, to, id);
require(to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT");
}
/// @notice Safely transfers `id` token from `from` to `to`.
/// @dev Requirements:
/// - `to` cannot be the zero address.
/// - `id` token must exist and be owned by `from`.
/// - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
/// - If `to` refers to a smart contract, it must implement {ERC721TokenReceiver-onERC721Received}, which is called upon a safe transfer.
/// Emits a {Transfer} event.
/// Additionally passes `data` in the callback.
/// @param from The address to transfer from.
/// @param to The address to transfer to.
/// @param id The token ID to transfer.
/// @param data The calldata to pass in the {ERC721TokenReceiver-onERC721Received} callback.
function safeTransferFrom(
address from,
address to,
uint256 id,
bytes memory data
) public virtual {
_transfer(from, to, id);
require(to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, data) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT");
}
/// @notice Returns the number of tokens in an account.
/// @param owner The address to query.
/// @return The balance.
function balanceOf(address owner) public view virtual returns (uint256);
/// @notice Returns the owner of a token ID.
/// @dev Requirements:
/// - `id` must exist.
/// @param id The token ID.
function ownerOf(uint256 id) public view virtual returns (address);
/* -------------------------------------------------------------------------- */
/* INTERNAL LOGIC */
/* -------------------------------------------------------------------------- */
/// @dev Returns whether a token ID exists.
/// Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
/// Tokens start existing when they are minted.
/// @param id Token ID to query.
function _exists(uint256 id) internal view virtual returns (bool);
/// @dev Transfers `id` from `from` to `to`.
/// Requirements:
/// - `to` cannot be the zero address.
/// - `id` token must be owned by `from`.
/// Emits a {Transfer} event.
/// @param from The address to transfer from.
/// @param to The address to transfer to.
/// @param id The token ID to transfer.
function _transfer(
address from,
address to,
uint256 id
) internal virtual;
/// @dev Mints `amount` tokens to `to`.
/// Requirements:
/// - there must be `amount` tokens remaining unminted in the total collection.
/// - `to` cannot be the zero address.
/// Emits `amount` {Transfer} events.
/// @param to The address to mint to.
/// @param amount The amount of tokens to mint.
function _mint(address to, uint256 amount) internal virtual;
/// @dev Safely mints `amount` of tokens and transfers them to `to`.
/// If `to` is a contract it must implement {ERC721TokenReceiver.onERC721Received}
/// that returns {ERC721TokenReceiver.onERC721Received.selector}.
/// @param to The address to mint to.
/// @param amount The amount of tokens to mint.
function _safeMint(address to, uint256 amount) internal virtual {
_mint(to, amount);
require(to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(address(0), to, totalSupply() - amount + 1, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT");
}
/// @dev Safely mints `amount` of tokens and transfers them to `to`.
/// Requirements:
/// - `id` must not exist.
/// - If `to` refers to a smart contract, it must implement {ERC721TokenReceiver.onERC721Received}, which is called upon a safe transfer.
/// Additionally passes `data` in the callback.
/// @param to The address to mint to.
/// @param amount The amount of tokens to mint.
/// @param data The calldata to pass in the {ERC721TokenReceiver.onERC721Received} callback.
function _safeMint(
address to,
uint256 amount,
bytes memory data
) internal virtual {
_mint(to, amount);
require(to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(address(0), to, totalSupply() - amount + 1, data) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT");
}
/* -------------------------------------------------------------------------- */
/* UTILS */
/* -------------------------------------------------------------------------- */
/// @notice Converts a `uint256` to its ASCII `string` decimal representation.
/// @dev https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol
function toString(uint256 value) internal pure virtual returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import { ERC721 } from "./ERC721.sol";
abstract contract ERC721M is ERC721 {
/* -------------------------------------------------------------------------- */
/* ERC721M STORAGE */
/* -------------------------------------------------------------------------- */
/// @dev The index is the token ID counter and points to its owner.
address[] internal _owners;
/* -------------------------------------------------------------------------- */
/* CONSTRUCTOR */
/* -------------------------------------------------------------------------- */
constructor(string memory name_, string memory symbol_) ERC721(name_, symbol_) {
// Initializes the index to 1.
_owners.push();
}
/* -------------------------------------------------------------------------- */
/* ENUMERABLE LOGIC */
/* -------------------------------------------------------------------------- */
/// @inheritdoc ERC721
function totalSupply() public view override returns (uint256) {
// Overflow is impossible as _owners.length is initialized to 1.
unchecked {
return _owners.length - 1;
}
}
/// @dev O(totalSupply), it is discouraged to call this function from other contracts
/// as it can become very expensive, especially with higher total collection sizes.
/// @inheritdoc ERC721
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < balanceOf(owner), "INVALID_INDEX");
// Both of the counters cannot overflow because the loop breaks before that.
unchecked {
uint256 count;
uint256 _currentIndex = _owners.length; // == totalSupply() + 1 == _owners.length - 1 + 1
for (uint256 i; i < _currentIndex; i++) {
if (owner == ownerOf(i)) {
if (count == index) return i;
else count++;
}
}
}
revert("NOT_FOUND");
}
/// @inheritdoc ERC721
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(_exists(index), "INVALID_INDEX");
return index;
}
/* -------------------------------------------------------------------------- */
/* ERC721 LOGIC */
/* -------------------------------------------------------------------------- */
/// @dev O(totalSupply), it is discouraged to call this function from other contracts
/// as it can become very expensive, especially with higher total collection sizes.
/// @inheritdoc ERC721
function balanceOf(address owner) public view virtual override returns (uint256 balance) {
require(owner != address(0), "INVALID_OWNER");
unchecked {
// Start at 1 since token 0 does not exist
uint256 _currentIndex = _owners.length; // == totalSupply() + 1 == _owners.length - 1 + 1
for (uint256 i = 1; i < _currentIndex; i++) {
if (owner == ownerOf(i)) {
balance++;
}
}
}
}
/// @dev O(MAX_TX), gradually moves to O(1) as more tokens get transferred and
/// the owners are explicitly set.
/// @inheritdoc ERC721
function ownerOf(uint256 id) public view virtual override returns (address owner) {
require(_exists(id), "NONEXISTENT_TOKEN");
for (uint256 i = id; ; i++) {
owner = _owners[i];
if (owner != address(0)) {
return owner;
}
}
}
/* -------------------------------------------------------------------------- */
/* INTERNAL LOGIC */
/* -------------------------------------------------------------------------- */
/// @inheritdoc ERC721
function _mint(address to, uint256 amount) internal virtual override {
require(to != address(0), "INVALID_RECIPIENT");
require(amount != 0, "INVALID_AMOUNT");
unchecked {
uint256 _currentIndex = _owners.length; // == totalSupply() + 1 == _owners.length - 1 + 1
for (uint256 i; i < amount - 1; i++) {
// storing address(0) while also incrementing the index
_owners.push();
emit Transfer(address(0), to, _currentIndex + i);
}
// storing the actual owner
_owners.push(to);
emit Transfer(address(0), to, _currentIndex + (amount - 1));
}
}
/// @inheritdoc ERC721
function _exists(uint256 id) internal view virtual override returns (bool) {
return id != 0 && id < _owners.length;
}
/// @inheritdoc ERC721
function _transfer(
address from,
address to,
uint256 id
) internal virtual override {
require(ownerOf(id) == from, "WRONG_FROM");
require(to != address(0), "INVALID_RECIPIENT");
require(msg.sender == from || getApproved(id) == msg.sender || isApprovedForAll(from, msg.sender), "NOT_AUTHORIZED");
delete _tokenApprovals[id];
_owners[id] = to;
unchecked {
uint256 prevId = id - 1;
if (_owners[prevId] == address(0)) {
_owners[prevId] = from;
}
}
emit Transfer(from, to, id);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { ERC721 } from "../ERC721.sol";
/// @notice An interface for the OpenSea Proxy Registry.
interface IProxyRegistry {
function proxies(address) external view returns (address);
}
abstract contract ERC721Tradable is ERC721 {
/* -------------------------------------------------------------------------- */
/* IMMUTABLE STORAGE */
/* -------------------------------------------------------------------------- */
/// @notice The OpenSea Proxy Registry address.
address public immutable openSeaProxyRegistry;
/// @notice The LooksRare Transfer Manager (ERC721) address.
address public immutable looksRareTransferManager;
/* -------------------------------------------------------------------------- */
/* MUTABLE STORAGE */
/* -------------------------------------------------------------------------- */
/// @notice Returns true if the stored marketplace addresses are whitelisted in {isApprovedForAll}.
/// @dev Enabled by default. Can be turned off with {setMarketplaceApprovalForAll}.
bool public marketPlaceApprovalForAll = true;
/* -------------------------------------------------------------------------- */
/* CONSTRUCTOR */
/* -------------------------------------------------------------------------- */
/// OpenSea proxy registry addresses:
/// - ETHEREUM MAINNET: 0xa5409ec958C83C3f309868babACA7c86DCB077c1
/// - ETHEREUM RINKEBY: 0xF57B2c51dED3A29e6891aba85459d600256Cf317
/// LooksRare Transfer Manager addresses (https://docs.looksrare.org/developers/deployed-contract-addresses):
/// - ETHEREUM MAINNET: 0xf42aa99F011A1fA7CDA90E5E98b277E306BcA83e
/// - ETHEREUM RINKEBY: 0x3f65A762F15D01809cDC6B43d8849fF24949c86a
/// @param _openSeaProxyRegistry The OpenSea proxy registry address.
constructor(address _openSeaProxyRegistry, address _looksRareTransferManager) {
require(_openSeaProxyRegistry != address(0) && _looksRareTransferManager != address(0), "INVALID_ADDRESS");
openSeaProxyRegistry = _openSeaProxyRegistry;
looksRareTransferManager = _looksRareTransferManager;
}
/* -------------------------------------------------------------------------- */
/* ERC721ATradable LOGIC */
/* -------------------------------------------------------------------------- */
/// @notice Enables or disables the marketplace whitelist in {isApprovedForAll}.
/// @dev Must be implemented in inheriting contracts.
/// Recommended to use in combination with an access control contract (e.g. OpenZeppelin's Ownable).
function setMarketplaceApprovalForAll(bool approved) public virtual;
/// @return True if `operator` is a whitelisted marketplace contract or if it was approved by `owner` with {ERC721A.setApprovalForAll}.
/// @inheritdoc ERC721
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
if (marketPlaceApprovalForAll && (operator == IProxyRegistry(openSeaProxyRegistry).proxies(owner) || operator == looksRareTransferManager)) return true;
return super.isApprovedForAll(owner, operator);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice A generic interface for a contract which properly accepts ERC721 tokens.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol)
interface ERC721TokenReceiver {
function onERC721Received(
address operator,
address from,
uint256 id,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
|
Approve or remove `operator` as an operator for the caller. Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. Emits an {ApprovalForAll} event. operator The address of the operator to approve. approved The status to set.
|
function setApprovalForAll(address operator, bool approved) public virtual {
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
| 10,176,524 |
./full_match/4/0x164c24d0844c267DA15a4c841eaBae817d211EA1/sources/Users/hristiyangeorgiev/Documents/Projects/Redemeum/ERC20/bsn-core-prototype/contracts/Cashier.sol
|
Internal function for withdrawing. As unbelievable as it is, neither .send() nor .transfer() are now secure to use due to EIP-1884 So now transferring funds via the last remaining option: .call() _recipient address of the account receiving funds from the escrow _amount amount to be released from escrow/
|
function _withdraw(address payable _recipient, uint256 _amount)
internal
{
require(_amount > 0, "");
_recipient.sendValue(_amount);
emit LogWithdrawal(msg.sender, _recipient, _amount);
}
| 13,350,827 |
./full_match/3/0x77AD263Cd578045105FBFC88A477CAd808d39Cf6/sources/contracts/UniswapV3Pool.sol
|
@inheritdoc IUniswapV3PoolDerivedState
|
function secondsInside(int24 tickLower, int24 tickUpper) external view override noDelegateCall returns (uint32) {
checkTicks(tickLower, tickUpper);
require(ticks[tickLower].liquidityGross > 0 && ticks[tickUpper].liquidityGross > 0, 'X');
return secondsOutside.secondsInside(tickLower, tickUpper, slot0.tick, tickSpacing, _blockTimestamp());
}
| 14,155,844 |
pragma solidity ^0.5.0;
// external modules
import "solidity-rlp/contracts/RLPReader.sol";
// libraries
import "./libraries/BytesUtil.sol";
import "./libraries/SafeMath.sol";
import "./libraries/ECDSA.sol";
import "./libraries/TMSimpleMerkleTree.sol";
import "./libraries/MinPriorityQueue.sol";
contract PlasmaMVP {
using MinPriorityQueue for uint256[];
using BytesUtil for bytes;
using RLPReader for bytes;
using RLPReader for RLPReader.RLPItem;
using SafeMath for uint256;
using TMSimpleMerkleTree for bytes32;
using ECDSA for bytes32;
/*
* Events
*/
event ChangedOperator(address oldOperator, address newOperator);
event AddedToBalances(address owner, uint256 amount);
event BlockSubmitted(bytes32 header, uint256 blockNumber, uint256 numTxns, uint256 feeAmount);
event Deposit(address depositor, uint256 amount, uint256 depositNonce, uint256 ethBlockNum);
event StartedTransactionExit(uint256[3] position, address owner, uint256 amount, bytes confirmSignatures, uint256 committedFee);
event StartedDepositExit(uint256 nonce, address owner, uint256 amount, uint256 committedFee);
event ChallengedExit(uint256[4] position, address owner, uint256 amount);
event FinalizedExit(uint256[4] position, address owner, uint256 amount);
/*
* Storage
*/
address public operator;
uint256 public lastCommittedBlock;
uint256 public depositNonce;
mapping(uint256 => plasmaBlock) public plasmaChain;
mapping(uint256 => depositStruct) public deposits;
struct plasmaBlock{
bytes32 header;
uint256 numTxns;
uint256 feeAmount;
uint256 createdAt;
}
struct depositStruct {
address owner;
uint256 amount;
uint256 createdAt;
uint256 ethBlockNum;
}
// exits
uint256 public minExitBond;
uint256[] public txExitQueue;
uint256[] public depositExitQueue;
mapping(uint256 => exit) public txExits;
mapping(uint256 => exit) public depositExits;
enum ExitState { NonExistent, Pending, Challenged, Finalized }
struct exit {
uint256 amount;
uint256 committedFee;
uint256 createdAt;
address owner;
uint256[4] position; // (blkNum, txIndex, outputIndex, depositNonce)
ExitState state; // default value is `NonExistent`
}
// funds
mapping(address => uint256) public balances;
uint256 public totalWithdrawBalance;
// constants
uint256 constant txIndexFactor = 10;
uint256 constant blockIndexFactor = 1000000;
uint256 constant lastBlockNum = 2**109;
uint256 constant feeIndex = 2**16-1;
/** Modifiers **/
modifier isBonded()
{
require(msg.value >= minExitBond);
if (msg.value > minExitBond) {
uint256 excess = msg.value.sub(minExitBond);
balances[msg.sender] = balances[msg.sender].add(excess);
totalWithdrawBalance = totalWithdrawBalance.add(excess);
}
_;
}
modifier onlyOperator()
{
require(msg.sender == operator);
_;
}
function changeOperator(address newOperator)
public
onlyOperator
{
require(newOperator != address(0));
emit ChangedOperator(operator, newOperator);
operator = newOperator;
}
constructor() public
{
operator = msg.sender;
lastCommittedBlock = 0;
depositNonce = 1;
minExitBond = 200000;
}
// @param blocks 32 byte merkle headers appended in ascending order
// @param txnsPerBlock number of transactions per block
// @param feesPerBlock amount of fees the validator has collected per block
// @param blockNum the block number of the first header
// @notice each block is capped at 2**16-1 transactions
function submitBlock(bytes32[] memory headers, uint256[] memory txnsPerBlock, uint256[] memory feePerBlock, uint256 blockNum)
public
onlyOperator
{
require(blockNum == lastCommittedBlock.add(1));
require(headers.length == txnsPerBlock.length && txnsPerBlock.length == feePerBlock.length);
for (uint i = 0; i < headers.length && lastCommittedBlock <= lastBlockNum; i++) {
require(headers[i] != bytes32(0) && txnsPerBlock[i] > 0 && txnsPerBlock[i] < feeIndex);
lastCommittedBlock = lastCommittedBlock.add(1);
plasmaChain[lastCommittedBlock] = plasmaBlock({
header: headers[i],
numTxns: txnsPerBlock[i],
feeAmount: feePerBlock[i],
createdAt: block.timestamp
});
emit BlockSubmitted(headers[i], lastCommittedBlock, txnsPerBlock[i], feePerBlock[i]);
}
}
// @param owner owner of this deposit
function deposit(address owner)
public
payable
{
deposits[depositNonce] = depositStruct(owner, msg.value, block.timestamp, block.number);
emit Deposit(owner, msg.value, depositNonce, block.number);
depositNonce = depositNonce.add(uint256(1));
}
// @param depositNonce the nonce of the specific deposit
function startDepositExit(uint256 nonce, uint256 committedFee)
public
payable
isBonded
{
require(deposits[nonce].owner == msg.sender);
require(deposits[nonce].amount > committedFee);
require(depositExits[nonce].state == ExitState.NonExistent);
address owner = deposits[nonce].owner;
uint256 amount = deposits[nonce].amount;
uint256 priority = block.timestamp << 128 | nonce;
depositExitQueue.insert(priority);
depositExits[nonce] = exit({
owner: owner,
amount: amount,
committedFee: committedFee,
createdAt: block.timestamp,
position: [0,0,0,nonce],
state: ExitState.Pending
});
emit StartedDepositExit(nonce, owner, amount, committedFee);
}
// Transaction encoding:
// [[Blknum1, TxIndex1, Oindex1, DepositNonce1, Input1ConfirmSig,
// Blknum2, TxIndex2, Oindex2, DepositNonce2, Input2ConfirmSig,
// NewOwner, Denom1, NewOwner, Denom2, Fee],
// [Signature1, Signature2]]
//
// All integers are padded to 32 bytes. Input's confirm signatures are 130 bytes for each input.
// Zero bytes if unapplicable (deposit/fee inputs) Signatures are 65 bytes in length
//
// @param txBytes rlp encoded transaction
// @notice this function will revert if the txBytes are malformed
function decodeTransaction(bytes memory txBytes)
internal
pure
returns (RLPReader.RLPItem[] memory txList, RLPReader.RLPItem[] memory sigList, bytes32 txHash)
{
// entire byte length of the rlp encoded transaction.
require(txBytes.length == 811);
RLPReader.RLPItem[] memory spendMsg = txBytes.toRlpItem().toList();
require(spendMsg.length == 2);
txList = spendMsg[0].toList();
require(txList.length == 15);
sigList = spendMsg[1].toList();
require(sigList.length == 2);
// bytes the signatures are over
txHash = keccak256(spendMsg[0].toRlpBytes());
}
// @param txPos location of the transaction [blkNum, txIndex, outputIndex]
// @param txBytes transaction bytes containing the exiting output
// @param proof merkle proof of inclusion in the plasma chain
// @param confSig0 confirm signatures sent by the owners of the first input acknowledging the spend.
// @param confSig1 confirm signatures sent by the owners of the second input acknowledging the spend (if applicable).
// @notice `confirmSignatures` and `ConfirmSig0`/`ConfirmSig1` are unrelated to each other.
// @notice `confirmSignatures` is either 65 or 130 bytes in length dependent on if a second input is present
// @notice `confirmSignatures` should be empty if the output trying to be exited is a fee output
function startTransactionExit(uint256[3] memory txPos, bytes memory txBytes, bytes memory proof, bytes memory confirmSignatures, uint256 committedFee)
public
payable
isBonded
{
require(txPos[1] < feeIndex);
uint256 position = calcPosition(txPos);
require(txExits[position].state == ExitState.NonExistent);
uint256 amount = startTransactionExitHelper(txPos, txBytes, proof, confirmSignatures);
require(amount > committedFee);
// calculate the priority of the transaction taking into account the withdrawal delay attack
// withdrawal delay attack: https://github.com/FourthState/plasma-mvp-rootchain/issues/42
uint256 createdAt = plasmaChain[txPos[0]].createdAt;
txExitQueue.insert(SafeMath.max(createdAt.add(1 weeks), block.timestamp) << 128 | position);
// write exit to storage
txExits[position] = exit({
owner: msg.sender,
amount: amount,
committedFee: committedFee,
createdAt: block.timestamp,
position: [txPos[0], txPos[1], txPos[2], 0],
state: ExitState.Pending
});
emit StartedTransactionExit(txPos, msg.sender, amount, confirmSignatures, committedFee);
}
// @returns amount of the exiting transaction
// @notice the purpose of this helper was to work around the capped evm stack frame
function startTransactionExitHelper(uint256[3] memory txPos, bytes memory txBytes, bytes memory proof, bytes memory confirmSignatures)
private
view
returns (uint256)
{
bytes32 txHash;
RLPReader.RLPItem[] memory txList;
RLPReader.RLPItem[] memory sigList;
(txList, sigList, txHash) = decodeTransaction(txBytes);
uint base = txPos[2].mul(2);
require(msg.sender == txList[base.add(10)].toAddress());
plasmaBlock memory blk = plasmaChain[txPos[0]];
// Validation
bytes32 merkleHash = sha256(txBytes);
require(merkleHash.checkMembership(txPos[1], blk.header, proof, blk.numTxns));
address recoveredAddress;
bytes32 confirmationHash = sha256(abi.encodePacked(merkleHash, blk.header));
bytes memory sig = sigList[0].toBytes();
require(sig.length == 65 && confirmSignatures.length % 65 == 0 && confirmSignatures.length > 0 && confirmSignatures.length <= 130);
recoveredAddress = confirmationHash.recover(confirmSignatures.slice(0, 65));
require(recoveredAddress != address(0) && recoveredAddress == txHash.recover(sig));
if (txList[5].toUintStrict() > 0 || txList[8].toUintStrict() > 0) { // existence of a second input
sig = sigList[1].toBytes();
require(sig.length == 65 && confirmSignatures.length == 130);
recoveredAddress = confirmationHash.recover(confirmSignatures.slice(65, 65));
require(recoveredAddress != address(0) && recoveredAddress == txHash.recover(sig));
}
// check that the UTXO's two direct inputs have not been previously exited
require(validateTransactionExitInputs(txList));
return txList[base.add(11)].toUintStrict();
}
// For any attempted exit of an UTXO, validate that the UTXO's two inputs have not
// been previously exited or are currently pending an exit.
function validateTransactionExitInputs(RLPReader.RLPItem[] memory txList)
private
view
returns (bool)
{
for (uint256 i = 0; i < 2; i++) {
ExitState state;
uint256 base = uint256(5).mul(i);
uint depositNonce_ = txList[base.add(3)].toUintStrict();
if (depositNonce_ == 0) {
uint256 blkNum = txList[base].toUintStrict();
uint256 txIndex = txList[base.add(1)].toUintStrict();
uint256 outputIndex = txList[base.add(2)].toUintStrict();
uint256 position = calcPosition([blkNum, txIndex, outputIndex]);
state = txExits[position].state;
} else
state = depositExits[depositNonce_].state;
if (state != ExitState.NonExistent && state != ExitState.Challenged)
return false;
}
return true;
}
// Validator of any block can call this function to exit the fees collected
// for that particular block. The fee exit is added to exit queue with the lowest priority for that block.
// In case of the fee UTXO already spent, anyone can challenge the fee exit by providing
// the spend of the fee UTXO.
// @param blockNumber the block for which the validator wants to exit fees
function startFeeExit(uint256 blockNumber, uint256 committedFee)
public
payable
onlyOperator
isBonded
{
plasmaBlock memory blk = plasmaChain[blockNumber];
require(blk.header != bytes32(0));
uint256 feeAmount = blk.feeAmount;
// nonzero fee and prevent and greater than the committed fee if spent.
// default value for a fee amount is zero. Will revert if a block for
// this number has not been committed
require(feeAmount > committedFee);
// a fee UTXO has explicitly defined position [blockNumber, 2**16 - 1, 0]
uint256 position = calcPosition([blockNumber, feeIndex, 0]);
require(txExits[position].state == ExitState.NonExistent);
txExitQueue.insert(SafeMath.max(blk.createdAt.add(1 weeks), block.timestamp) << 128 | position);
txExits[position] = exit({
owner: msg.sender,
amount: feeAmount,
committedFee: committedFee,
createdAt: block.timestamp,
position: [blockNumber, feeIndex, 0, 0],
state: ExitState.Pending
});
// pass in empty bytes for confirmSignatures for StartedTransactionExit event.
emit StartedTransactionExit([blockNumber, feeIndex, 0], operator, feeAmount, "", 0);
}
// @param exitingTxPos position of the invalid exiting transaction [blkNum, txIndex, outputIndex]
// @param challengingTxPos position of the challenging transaction [blkNum, txIndex]
// @param txBytes raw transaction bytes of the challenging transaction
// @param proof proof of inclusion for this merkle hash
// @param confirmSignature signature used to invalidate the invalid exit. Signature is over (merkleHash, block header)
// @notice The operator can challenge an exit which commits an invalid fee by simply passing in empty bytes for confirm signature as they are not needed.
// The committed fee is checked againt the challenging tx bytes
function challengeExit(uint256[4] memory exitingTxPos, uint256[2] memory challengingTxPos, bytes memory txBytes, bytes memory proof, bytes memory confirmSignature)
public
{
bytes32 txHash;
RLPReader.RLPItem[] memory txList;
RLPReader.RLPItem[] memory sigList;
(txList, sigList, txHash) = decodeTransaction(txBytes);
// `challengingTxPos` is sequentially after `exitingTxPos`
require(exitingTxPos[0] < challengingTxPos[0] || (exitingTxPos[0] == challengingTxPos[0] && exitingTxPos[1] < challengingTxPos[1]));
// must be a direct spend
bool firstInput = exitingTxPos[0] == txList[0].toUintStrict() && exitingTxPos[1] == txList[1].toUintStrict() && exitingTxPos[2] == txList[2].toUintStrict() && exitingTxPos[3] == txList[3].toUintStrict();
require(firstInput || exitingTxPos[0] == txList[5].toUintStrict() && exitingTxPos[1] == txList[6].toUintStrict() && exitingTxPos[2] == txList[7].toUintStrict() && exitingTxPos[3] == txList[8].toUintStrict());
// transaction to be challenged should have a pending exit
exit storage exit_ = exitingTxPos[3] == 0 ?
txExits[calcPosition([exitingTxPos[0], exitingTxPos[1], exitingTxPos[2]])] : depositExits[exitingTxPos[3]];
require(exit_.state == ExitState.Pending);
plasmaBlock memory blk = plasmaChain[challengingTxPos[0]];
bytes32 merkleHash = sha256(txBytes);
require(blk.header != bytes32(0) && merkleHash.checkMembership(challengingTxPos[1], blk.header, proof, blk.numTxns));
address recoveredAddress;
// we check for confirm signatures if:
// The exiting tx is a first input and commits the correct fee
// OR
// The exiting tx is the second input in the challenging transaction
//
// If this challenge was a fee mismatch, then we check the first transaction signature
// to prevent the operator from forging invalid inclusions
//
// For a fee mismatch, the state becomes `NonExistent` so that the exit can be reopened.
// Otherwise, `Challenged` so that the exit can never be opened.
if (firstInput && exit_.committedFee != txList[14].toUintStrict()) {
bytes memory sig = sigList[0].toBytes();
recoveredAddress = txHash.recover(sig);
require(sig.length == 65 && recoveredAddress != address(0) && exit_.owner == recoveredAddress);
exit_.state = ExitState.NonExistent;
} else {
bytes32 confirmationHash = sha256(abi.encodePacked(merkleHash, blk.header));
recoveredAddress = confirmationHash.recover(confirmSignature);
require(confirmSignature.length == 65 && recoveredAddress != address(0) && exit_.owner == recoveredAddress);
exit_.state = ExitState.Challenged;
}
// exit successfully challenged. Award the sender with the bond
balances[msg.sender] = balances[msg.sender].add(minExitBond);
totalWithdrawBalance = totalWithdrawBalance.add(minExitBond);
emit AddedToBalances(msg.sender, minExitBond);
emit ChallengedExit(exit_.position, exit_.owner, exit_.amount - exit_.committedFee);
}
function finalizeDepositExits() public { finalize(depositExitQueue, true); }
function finalizeTransactionExits() public { finalize(txExitQueue, false); }
// Finalizes exits by iterating through either the depositExitQueue or txExitQueue.
// Users can determine the number of exits they're willing to process by varying
// the amount of gas allow finalize*Exits() to process.
// Each transaction takes < 80000 gas to process.
function finalize(uint256[] storage queue, bool isDeposits)
private
{
if (queue.length == 0) return;
// retrieve the lowest priority and the appropriate exit struct
uint256 priority = queue[0];
exit memory currentExit;
uint256 position;
// retrieve the right 128 bits from the priority to obtain the position
assembly {
position := and(priority, div(not(0x0), exp(256, 16)))
}
currentExit = isDeposits ? depositExits[position] : txExits[position];
/*
* Conditions:
* 1. Exits exist
* 2. Exits must be a week old
* 3. Funds must exist for the exit to withdraw
*/
uint256 amountToAdd;
uint256 challengePeriod = isDeposits ? 5 days : 1 weeks;
while (block.timestamp.sub(currentExit.createdAt) > challengePeriod &&
plasmaChainBalance() > 0 &&
gasleft() > 80000) {
// skip currentExit if it is not in 'started/pending' state.
if (currentExit.state != ExitState.Pending) {
queue.delMin();
} else {
// reimburse the bond but remove fee allocated for the operator
amountToAdd = currentExit.amount.add(minExitBond).sub(currentExit.committedFee);
balances[currentExit.owner] = balances[currentExit.owner].add(amountToAdd);
totalWithdrawBalance = totalWithdrawBalance.add(amountToAdd);
if (isDeposits)
depositExits[position].state = ExitState.Finalized;
else
txExits[position].state = ExitState.Finalized;
emit FinalizedExit(currentExit.position, currentExit.owner, amountToAdd);
emit AddedToBalances(currentExit.owner, amountToAdd);
// move onto the next oldest exit
queue.delMin();
}
if (queue.length == 0) {
return;
}
// move onto the next oldest exit
priority = queue[0];
// retrieve the right 128 bits from the priority to obtain the position
assembly {
position := and(priority, div(not(0x0), exp(256, 16)))
}
currentExit = isDeposits ? depositExits[position] : txExits[position];
}
}
// @notice will revert if the output index is out of bounds
function calcPosition(uint256[3] memory txPos)
private
view
returns (uint256)
{
require(validatePostion([txPos[0], txPos[1], txPos[2], 0]));
uint256 position = txPos[0].mul(blockIndexFactor).add(txPos[1].mul(txIndexFactor)).add(txPos[2]);
require(position <= 2**128-1); // check for an overflow
return position;
}
function validatePostion(uint256[4] memory position)
private
view
returns (bool)
{
uint256 blkNum = position[0];
uint256 txIndex = position[1];
uint256 oIndex = position[2];
uint256 depNonce = position[3];
if (blkNum > 0) { // utxo input
// uncommitted block
if (blkNum > lastCommittedBlock)
return false;
// txIndex out of bounds for the block
if (txIndex >= plasmaChain[blkNum].numTxns && txIndex != feeIndex)
return false;
// fee input must have a zero output index
if (txIndex == feeIndex && oIndex > 0)
return false;
// deposit nonce must be zero
if (depNonce > 0)
return false;
// only two outputs
if (oIndex > 1)
return false;
} else { // deposit or fee input
// deposit input must be zero'd output position
// `blkNum` is not checked as it will fail above
if (depNonce > 0 && (txIndex > 0 || oIndex > 0))
return false;
}
return true;
}
function withdraw()
public
returns (uint256)
{
if (balances[msg.sender] == 0) {
return 0;
}
uint256 transferAmount = balances[msg.sender];
delete balances[msg.sender];
totalWithdrawBalance = totalWithdrawBalance.sub(transferAmount);
// will revert the above deletion if it fails
msg.sender.transfer(transferAmount);
return transferAmount;
}
/*
* Getters
*/
function plasmaChainBalance()
public
view
returns (uint)
{
// takes into accounts the failed withdrawals
return address(this).balance - totalWithdrawBalance;
}
function balanceOf(address _address)
public
view
returns (uint256)
{
return balances[_address];
}
function txQueueLength()
public
view
returns (uint)
{
return txExitQueue.length;
}
function depositQueueLength()
public
view
returns (uint)
{
return depositExitQueue.length;
}
}
|
depositNonce the nonce of the specific deposit
|
function startDepositExit(uint256 nonce, uint256 committedFee)
public
payable
isBonded
{
require(deposits[nonce].owner == msg.sender);
require(deposits[nonce].amount > committedFee);
require(depositExits[nonce].state == ExitState.NonExistent);
address owner = deposits[nonce].owner;
uint256 amount = deposits[nonce].amount;
uint256 priority = block.timestamp << 128 | nonce;
depositExitQueue.insert(priority);
depositExits[nonce] = exit({
owner: owner,
amount: amount,
committedFee: committedFee,
createdAt: block.timestamp,
position: [0,0,0,nonce],
state: ExitState.Pending
});
emit StartedDepositExit(nonce, owner, amount, committedFee);
}
| 12,872,236 |
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/math/Math.sol
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/AccessControl.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Capped.sol
pragma solidity ^0.6.0;
/**
* @dev Extension of {ERC20} that adds a cap to the supply of tokens.
*/
abstract contract ERC20Capped is ERC20 {
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
constructor (uint256 cap) public {
require(cap > 0, "ERC20Capped: cap is 0");
_cap = cap;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - minted tokens must not cause the total supply to go over the cap.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) { // When minting tokens
require(totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded");
}
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/ChickenToken.sol
pragma solidity 0.6.12;
// ChickenToken with Governance. Capped at 580,000,000 supply.
contract ChickenToken is ERC20Capped, Ownable {
constructor() public ERC20("ChickenToken", "CHKN") ERC20Capped(580000000000000000000000000) { }
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (FryCook).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "CHKN::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "CHKN::delegateBySig: invalid nonce");
require(now <= expiry, "CHKN::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CHKN::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying CHKNs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "CHKN::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// File: contracts/FryCook.sol
pragma solidity 0.6.12;
// An interface for a future component of the CHKN system, allowing migration
// from one type of LP token to another. Migration moves liquidity from an exchange
// contract to another, e.g. for a swap version update. All users keep their
// staked liquidity and can deposit or withdraw the new type of token
// (kept in the same pool / pid) afterwards.
interface ICookMigrator {
// Perform LP token migration from UniswapV2 to ChickenFarm.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// ChickenFarm must mint EXACTLY the same amount of ChickenFarm LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrate(IERC20 token) external returns (IERC20);
}
// FryCook works the fryer. They make some good chicken!
//
// Note that there is an EXECUTIVE_ROLE and the executive(s) wields tremendous
// power. The deployer will have executive power until initial setup is complete,
// then renounce that direct power in favor of Timelocked control so the community
// can see incoming executive orders (including role changes). Eventually, this
// setup will be replaced with community governance by CHKN token holders.
//
// Executives determine who holds other roles and set contract references
// (e.g. for migration). The other roles are:
//
// Head Chef: Designs the menu (can add and update lp token pools)
// Sous Chef: Tweaks recipes (can update lp token pool allocation points)
// Waitstaff: Carries orders and payments (can deposit / withdraw on behalf of stakers)
//
// It makes sense for an executive (individual or community) to also operate as the
// head chef, but nothing but a well-tested and audited smart contract should EVER be assigned
// to waitstaff. Waitstaff have full access to all staked tokens.
contract FryCook is AccessControl {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. CHKNs to distribute per block.
uint256 lastRewardBlock; // Last block number that CHKNs distribution occurs.
uint256 totalScore; // Total score of all investors.
uint256 accChickenPerScore; // Accumulated CHKNs per score, times 1e12. See below.
// early bird point rewards (larger share of CHKN mints w/in the pool)
uint256 earlyBirdMinShares;
uint256 earlyBirdExtra;
uint256 earlyBirdGraceEndBlock;
uint256 earlyBirdHalvingBlocks;
}
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 score; // The staked "score" based on LP tokens and early bird bonus
uint256 earlyBirdMult; // Early bird bonus multiplier, scaled by EARLY_BIRD_PRECISION
bool earlyBird; // Does the score include an early bird bonus?
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of CHKNs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.score * pool.accChickenPerScore) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accChickenPerScore` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` and `score` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Access Control Roles. This is the FryCook, but there's other jobs in the kitchen.
bytes32 public constant EXECUTIVE_ROLE = keccak256("EXECUTIVE_ROLE"); // aka owner: determines other roles
bytes32 public constant HEAD_CHEF_ROLE = keccak256("HEAD_CHEF_ROLE"); // governance: token pool changes, control over agent list
bytes32 public constant SOUS_CHEF_ROLE = keccak256("SOUS_CHEF_ROLE"); // pool spiciness tweaks: can change allocation points for pools
bytes32 public constant WAITSTAFF_ROLE = keccak256("WAITSTAFF_ROLE"); // token agent(s): can make deposits / withdrawals on behalf of stakers
// The CHKN TOKEN!
ChickenToken public chicken;
uint256 public chickenCap;
// Dev address.
address public devaddr;
// Block number when bonus CHKN stage ends (staged decline to no bonus).
uint256 public bonusStage2Block;
uint256 public bonusStage3Block;
uint256 public bonusStage4Block;
uint256 public bonusEndBlock;
// CHKN tokens created per block.
uint256 public chickenPerBlock;
// Bonus muliplier for early chicken makers.
uint256 public constant BONUS_MULTIPLIER_STAGE_1 = 20;
uint256 public constant BONUS_MULTIPLIER_STAGE_2 = 15;
uint256 public constant BONUS_MULTIPLIER_STAGE_3 = 10;
uint256 public constant BONUS_MULTIPLIER_STAGE_4 = 5;
// Block number when dev share declines (staged decline to lowest share).
uint256 public devBonusStage2Block;
uint256 public devBonusStage3Block;
uint256 public devBonusStage4Block;
uint256 public devBonusEndBlock;
// Dev share divisor for each bonus stage.
uint256 public constant DEV_DIV_STAGE_1 = 10; // 10%
uint256 public constant DEV_DIV_STAGE_2 = 12; // 8.333..%
uint256 public constant DEV_DIV_STAGE_3 = 16; // 6.25%
uint256 public constant DEV_DIV_STAGE_4 = 25; // 4%
uint256 public constant DEV_DIV = 50; // 2%
// Precision values
uint256 public constant EARLY_BIRD_PRECISION = 1e12;
uint256 public constant ACC_CHICKEN_PRECISION = 1e12;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
ICookMigrator public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
mapping (address => uint256) public tokenPid;
mapping (address => bool) public hasToken;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when CHKN mining starts.
uint256 public startBlock;
event Deposit(address indexed staker, address indexed funder, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed staker, address indexed agent, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
ChickenToken _chicken,
address _devaddr,
uint256 _chickenPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock,
uint256 _devBonusEndBlock
) public {
chicken = _chicken;
devaddr = _devaddr;
chickenPerBlock = _chickenPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
devBonusEndBlock = _devBonusEndBlock;
// calculate mint bonus stage blocks (block-of-transition from 20x to 15x, etc.)
uint256 bonusStep = bonusEndBlock.sub(startBlock).div(4);
bonusStage2Block = bonusStep.add(startBlock);
bonusStage3Block = bonusStep.mul(2).add(startBlock);
bonusStage4Block = bonusStep.mul(3).add(startBlock);
// calculate dev divisor stage blocks
uint256 devBonusStep = devBonusEndBlock.sub(startBlock).div(4);
devBonusStage2Block = devBonusStep.add(startBlock);
devBonusStage3Block = devBonusStep.mul(2).add(startBlock);
devBonusStage4Block = devBonusStep.mul(3).add(startBlock);
// set up initial roles (caller is owner and manager). The caller
// CANNOT act as waitstaff; athough they can add and modify pools,
// they CANNOT touch user deposits. Nothing but another smart contract
// should ever be waitstaff.
_setupRole(EXECUTIVE_ROLE, msg.sender); // can manage other roles and link contracts
_setupRole(HEAD_CHEF_ROLE, msg.sender); // can create and alter pools
// set up executives as role administrators.
// after initial setup, all roles are expected to be served by other contracts
// (e.g. Timelock, GovernorAlpha, etc.)
_setRoleAdmin(EXECUTIVE_ROLE, EXECUTIVE_ROLE);
_setRoleAdmin(HEAD_CHEF_ROLE, EXECUTIVE_ROLE);
_setRoleAdmin(SOUS_CHEF_ROLE, EXECUTIVE_ROLE);
_setRoleAdmin(WAITSTAFF_ROLE, EXECUTIVE_ROLE);
// store so we never have to query again
chickenCap = chicken.cap();
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by a manager.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
uint256 _earlyBirdMinShares,
uint256 _earlyBirdInitialBonus,
uint256 _earlyBirdGraceEndBlock,
uint256 _earlyBirdHalvingBlocks,
bool _withUpdate
) public {
require(hasRole(HEAD_CHEF_ROLE, msg.sender), "FryCook::add: not authorized");
require(!hasToken[address(_lpToken)], "FryCook::add: lpToken already added");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
hasToken[address(_lpToken)] = true;
tokenPid[address(_lpToken)] = poolInfo.length;
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
earlyBirdMinShares: _earlyBirdMinShares,
earlyBirdExtra: _earlyBirdInitialBonus.sub(1), // provided as multiplier: 100x. Declines to 1x, so "99" extra.
earlyBirdGraceEndBlock: _earlyBirdGraceEndBlock,
earlyBirdHalvingBlocks: _earlyBirdHalvingBlocks,
lastRewardBlock: lastRewardBlock,
totalScore: 0,
accChickenPerScore: 0
}));
}
// Update the given pool's CHKN allocation point. Can only be called by a manager.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public {
require(hasRole(HEAD_CHEF_ROLE, msg.sender) || hasRole(SOUS_CHEF_ROLE, msg.sender), "FryCook::set: not authorized");
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by a manager.
function setMigrator(ICookMigrator _migrator) public {
require(hasRole(EXECUTIVE_ROLE, msg.sender), "FryCook::setMigrator: not authorized");
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "FryCook::migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "FryCook::migrate: bad");
pool.lpToken = newLpToken;
tokenPid[address(newLpToken)] = _pid;
hasToken[address(newLpToken)] = true;
tokenPid[address(lpToken)] = 0;
hasToken[address(lpToken)] = false;
}
// Return the number of blocks intersecting between the two ranges.
// Assumption: _from <= _to, _from2 <= _to2.
function getIntersection(uint256 _from, uint256 _to, uint256 _from2, uint256 _to2) public pure returns (uint256) {
if (_to <= _from2) {
return 0;
} else if (_to2 <= _from) {
return 0;
} else {
return Math.min(_to, _to2).sub(Math.max(_from, _from2));
}
}
// Return CHKN reward (mint) multiplier over the given range, _from to _to block.
// Multiply against chickenPerBlock to determine the total amount minted
// during that time (not including devaddr share). Ignores "startBlock".
// Assumption: _from <= _to. Otherwise get weird results.
function getMintMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_from >= bonusEndBlock) { // no bonus
return _to.sub(_from);
} else { // potentially intersect four bonus periods and/or "no bonus"
uint256 mult = 0;
mult = mult.add(getIntersection(_from, _to, 0, bonusStage2Block).mul(BONUS_MULTIPLIER_STAGE_1));
mult = mult.add(getIntersection(_from, _to, bonusStage2Block, bonusStage3Block).mul(BONUS_MULTIPLIER_STAGE_2));
mult = mult.add(getIntersection(_from, _to, bonusStage3Block, bonusStage4Block).mul(BONUS_MULTIPLIER_STAGE_3));
mult = mult.add(getIntersection(_from, _to, bonusStage4Block, bonusEndBlock).mul(BONUS_MULTIPLIER_STAGE_4));
mult = mult.add(Math.max(_to, bonusEndBlock).sub(bonusEndBlock)); // known: _from < bonusEndBlock
return mult;
}
}
// Returns the divisor to determine the developer's share of coins at the
// given block. For M coins minted, dev gets M.div(_val_). For a block range,
// undershoot by providing _to block (dev gets up to, not over, the bonus amount).
function getDevDivisor(uint256 _block) public view returns (uint256) {
if (_block >= devBonusEndBlock) {
return DEV_DIV;
} else if (_block >= devBonusStage4Block) {
return DEV_DIV_STAGE_4;
} else if (_block >= devBonusStage3Block) {
return DEV_DIV_STAGE_3;
} else if (_block >= devBonusStage2Block) {
return DEV_DIV_STAGE_2;
} else {
return DEV_DIV_STAGE_1;
}
}
// Returns the score multiplier for an early bird investor who qualifies
// at _block for _pid. The investment quantity and min threshold are not
// checked; qualification is a precondition.
// The output is scaled by EARLY_BIRD_PRECISION; e.g. a return value of
// 1.5 * EARLY_BIRD_PRECISION indicates a multiplier of 1.5x.
function getEarlyBirdMultiplier(uint256 _block, uint256 _pid) public view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
uint256 decliningPortion = pool.earlyBirdExtra.mul(EARLY_BIRD_PRECISION);
if (_block <= pool.earlyBirdGraceEndBlock) {
return decliningPortion.add(EARLY_BIRD_PRECISION);
}
uint256 distance = _block.sub(pool.earlyBirdGraceEndBlock);
uint256 halvings = distance.div(pool.earlyBirdHalvingBlocks); // whole number
if (halvings >= 120) { // asymptotic, up to a point
return EARLY_BIRD_PRECISION; // 1x
}
// approximate exponential decay with linear interpolation between integer exponents
uint256 progress = distance.sub(halvings.mul(pool.earlyBirdHalvingBlocks));
uint256 divisor = (2 ** halvings).mul(1e8); // scaled once for precision
uint256 nextDivisor = (2 ** (halvings.add(1))).mul(1e8); // scaled once for precision
uint256 diff = nextDivisor.sub(divisor);
uint256 alpha = progress.mul(1e8).div(pool.earlyBirdHalvingBlocks); // scaled once for precision
divisor = divisor.add(diff.mul(alpha).div(1e8)); // unscale alpha after mult. to keep precision
// divisor is scaled up; scale up declining portion by same amount before division
return decliningPortion.mul(1e8).div(divisor).add(EARLY_BIRD_PRECISION);
}
// View function to see pending CHKNs on frontend.
function pendingChicken(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accChickenPerScore = pool.accChickenPerScore;
uint256 totalScore = pool.totalScore;
if (block.number > pool.lastRewardBlock && totalScore != 0) {
uint256 multiplier = getMintMultiplier(pool.lastRewardBlock, block.number);
uint256 chickenReward = multiplier.mul(chickenPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accChickenPerScore = accChickenPerScore.add(chickenReward.mul(ACC_CHICKEN_PRECISION).div(totalScore));
}
return user.score.mul(accChickenPerScore).div(ACC_CHICKEN_PRECISION).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 totalScore = pool.totalScore;
if (totalScore == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMintMultiplier(pool.lastRewardBlock, block.number);
uint256 chickenReward = multiplier.mul(chickenPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
uint256 devReward = chickenReward.div(getDevDivisor(block.number));
uint256 supply = chicken.totalSupply();
// safe mint: don't exceed supply
if (supply.add(chickenReward).add(devReward) > chickenCap) {
chickenReward = chickenCap.sub(supply);
devReward = 0;
}
chicken.mint(address(this), chickenReward);
chicken.mint(devaddr, devReward);
pool.accChickenPerScore = pool.accChickenPerScore.add(chickenReward.mul(ACC_CHICKEN_PRECISION).div(totalScore));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to FryCook for CHKN allocation. Deposit 0 to bump a pool update.
function deposit(uint256 _pid, uint256 _amount) public {
_deposit(_pid, _amount, msg.sender, msg.sender);
}
// Deposit LP tokens on behalf of another user.
function depositTo(uint256 _pid, uint256 _amount, address _staker) public {
require(hasRole(WAITSTAFF_ROLE, msg.sender), "FryCook::depositTo: not authorized");
_deposit(_pid, _amount, _staker, msg.sender);
}
// Handle deposits, whether agent-driven or user-initiated.
function _deposit(uint256 _pid, uint256 _amount, address _staker, address _funder) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_staker];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.score.mul(pool.accChickenPerScore).div(ACC_CHICKEN_PRECISION).sub(user.rewardDebt);
if (pending > 0) {
safeChickenTransfer(_staker, pending);
}
} else {
user.earlyBirdMult = EARLY_BIRD_PRECISION; // equiv. to 1x
}
// transfer LP tokens; update user info
if (_amount > 0) {
pool.lpToken.safeTransferFrom(_funder, address(this), _amount);
uint256 oldScore = user.score;
user.amount = user.amount.add(_amount);
if (!user.earlyBird && user.amount >= pool.earlyBirdMinShares) {
user.earlyBird = true;
user.earlyBirdMult = getEarlyBirdMultiplier(block.number, _pid); // scaled
}
user.score = user.amount.mul(user.earlyBirdMult).div(EARLY_BIRD_PRECISION); // unscale
pool.totalScore = pool.totalScore.add(user.score).sub(oldScore);
}
// update dept regardless of whether score changes or deposit is > 0
user.rewardDebt = user.score.mul(pool.accChickenPerScore).div(ACC_CHICKEN_PRECISION);
emit Deposit(_staker, _funder, _pid, _amount);
}
// Withdraw staked LP tokens from FryCook. Also transfers pending chicken.
function withdraw(uint256 _pid, uint256 _amount) public {
_withdraw(_pid, _amount, address(msg.sender), address(msg.sender));
}
// Withdraw a user's staked LP tokens as an agent. Also transfers pending
// chicken (to the staking user, NOT the agent).
function withdrawFrom(uint256 _pid, uint256 _amount, address _staker) public {
require(hasRole(WAITSTAFF_ROLE, msg.sender), "FryCook::withdrawFrom: not authorized");
_withdraw(_pid, _amount, _staker, address(msg.sender));
}
// Withdraw LP tokens from FryCook to the agent. Staked chicken
// goes to the _staker. We don't support deferred CHKN transfers; every time
// a deposit or withdrawal happens, pending CHKN must be transferred or
// the books aren't kept clean.
function _withdraw(uint256 _pid, uint256 _amount, address _staker, address _agent) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_staker];
require(user.amount >= _amount, "FryCook::withdraw: not good");
updatePool(_pid);
uint256 pending = user.score.mul(pool.accChickenPerScore).div(ACC_CHICKEN_PRECISION).sub(user.rewardDebt);
if (pending > 0) {
safeChickenTransfer(_staker, pending);
}
// update user info
if (_amount > 0) {
uint256 oldScore = user.score;
user.amount = user.amount.sub(_amount);
if (user.earlyBird && user.amount < pool.earlyBirdMinShares) {
user.earlyBird = false;
user.earlyBirdMult = EARLY_BIRD_PRECISION;
}
user.score = user.amount.mul(user.earlyBirdMult).div(EARLY_BIRD_PRECISION); // unscale
pool.lpToken.safeTransfer(_agent, _amount);
pool.totalScore = pool.totalScore.add(user.score).sub(oldScore);
}
// update reward debt regardless of whether score changed, since debt may have
user.rewardDebt = user.score.mul(pool.accChickenPerScore).div(ACC_CHICKEN_PRECISION);
emit Withdraw(_staker, _agent, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
pool.totalScore = pool.totalScore.sub(user.score);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.earlyBird = false;
user.earlyBirdMult = EARLY_BIRD_PRECISION;
user.score = 0;
user.rewardDebt = 0;
}
// Safe chicken transfer function, just in case if rounding error causes pool to not have enough CHKNs.
function safeChickenTransfer(address _to, uint256 _amount) internal {
uint256 chickenBal = chicken.balanceOf(address(this));
if (_amount > chickenBal) {
chicken.transfer(_to, chickenBal);
} else {
chicken.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "FryCook::dev: wut?");
devaddr = _devaddr;
}
}
|
Withdraw a user's staked LP tokens as an agent. Also transfers pending chicken (to the staking user, NOT the agent).
|
function withdrawFrom(uint256 _pid, uint256 _amount, address _staker) public {
require(hasRole(WAITSTAFF_ROLE, msg.sender), "FryCook::withdrawFrom: not authorized");
_withdraw(_pid, _amount, _staker, address(msg.sender));
}
| 14,410,131 |
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {
OwnableUpgradeSafe
} from "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
import {
ReentrancyGuardUpgradeSafe
} from "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import {
PausableUpgradeSafe
} from "@openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol";
import {
Initializable
} from "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {
ERC20UpgradeSafe
} from "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol";
import {
SafeMath
} from "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import {
AggregatorV3Interface
} from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import {ILiquidityPool} from "./ILiquidityPool.sol";
import {IDetailedERC20} from "contracts/common/Imports.sol";
/**
* @notice Old version of the `PoolToken`
* @notice Should not be used in deployment
*/
contract PoolToken is
ILiquidityPool,
Initializable,
OwnableUpgradeSafe,
ReentrancyGuardUpgradeSafe,
PausableUpgradeSafe,
ERC20UpgradeSafe
{
using SafeMath for uint256;
using SafeERC20 for IDetailedERC20;
uint256 public constant DEFAULT_APT_TO_UNDERLYER_FACTOR = 1000;
/* ------------------------------- */
/* impl-specific storage variables */
/* ------------------------------- */
address public proxyAdmin;
bool public addLiquidityLock;
bool public redeemLock;
IDetailedERC20 public underlyer;
AggregatorV3Interface public priceAgg;
/* ------------------------------- */
modifier onlyAdmin() {
require(msg.sender == proxyAdmin, "ADMIN_ONLY");
_;
}
receive() external payable {
revert("DONT_SEND_ETHER");
}
function initialize(
address adminAddress,
IDetailedERC20 _underlyer,
AggregatorV3Interface _priceAgg
) external initializer {
require(adminAddress != address(0), "INVALID_ADMIN");
require(address(_underlyer) != address(0), "INVALID_TOKEN");
require(address(_priceAgg) != address(0), "INVALID_AGG");
// initialize ancestor storage
__Context_init_unchained();
__Ownable_init_unchained();
__ReentrancyGuard_init_unchained();
__Pausable_init_unchained();
__ERC20_init_unchained("APY Pool Token", "APT");
// initialize impl-specific storage
setAdminAddress(adminAddress);
addLiquidityLock = false;
redeemLock = false;
underlyer = _underlyer;
setPriceAggregator(_priceAgg);
}
// solhint-disable-next-line no-empty-blocks
function initializeUpgrade() external virtual onlyAdmin {}
function lock() external onlyOwner {
_pause();
}
function unlock() external onlyOwner {
_unpause();
}
/**
* @notice Mint corresponding amount of APT tokens for sent token amount.
* @dev If no APT tokens have been minted yet, fallback to a fixed ratio.
*/
function addLiquidity(uint256 tokenAmt)
external
virtual
override
nonReentrant
whenNotPaused
{
require(!addLiquidityLock, "LOCKED");
require(tokenAmt > 0, "AMOUNT_INSUFFICIENT");
require(
underlyer.allowance(msg.sender, address(this)) >= tokenAmt,
"ALLOWANCE_INSUFFICIENT"
);
// calculateMintAmount() is not used because deposit value
// is needed for the event
uint256 depositEthValue = getEthValueFromTokenAmount(tokenAmt);
uint256 poolTotalEthValue = getPoolTotalEthValue();
uint256 mintAmount =
_calculateMintAmount(depositEthValue, poolTotalEthValue);
_mint(msg.sender, mintAmount);
underlyer.safeTransferFrom(msg.sender, address(this), tokenAmt);
emit DepositedAPT(
msg.sender,
underlyer,
tokenAmt,
mintAmount,
depositEthValue,
getPoolTotalEthValue()
);
}
/** @notice Disable deposits. */
function lockAddLiquidity() external onlyOwner {
addLiquidityLock = true;
emit AddLiquidityLocked();
}
/** @notice Enable deposits. */
function unlockAddLiquidity() external onlyOwner {
addLiquidityLock = false;
emit AddLiquidityUnlocked();
}
/**
* @notice Redeems APT amount for its underlying token amount.
* @param aptAmount The amount of APT tokens to redeem
*/
function redeem(uint256 aptAmount)
external
virtual
override
nonReentrant
whenNotPaused
{
require(!redeemLock, "LOCKED");
require(aptAmount > 0, "AMOUNT_INSUFFICIENT");
require(aptAmount <= balanceOf(msg.sender), "BALANCE_INSUFFICIENT");
uint256 redeemTokenAmt = getUnderlyerAmount(aptAmount);
_burn(msg.sender, aptAmount);
underlyer.safeTransfer(msg.sender, redeemTokenAmt);
emit RedeemedAPT(
msg.sender,
underlyer,
redeemTokenAmt,
aptAmount,
getEthValueFromTokenAmount(redeemTokenAmt),
getPoolTotalEthValue()
);
}
/** @notice Disable APT redeeming. */
function lockRedeem() external onlyOwner {
redeemLock = true;
emit RedeemLocked();
}
/** @notice Enable APT redeeming. */
function unlockRedeem() external onlyOwner {
redeemLock = false;
emit RedeemUnlocked();
}
function setAdminAddress(address adminAddress) public onlyOwner {
require(adminAddress != address(0), "INVALID_ADMIN");
proxyAdmin = adminAddress;
emit AdminChanged(adminAddress);
}
function setPriceAggregator(AggregatorV3Interface _priceAgg)
public
onlyOwner
{
require(address(_priceAgg) != address(0), "INVALID_AGG");
priceAgg = _priceAgg;
emit PriceAggregatorChanged(address(_priceAgg));
}
/**
* @notice Calculate APT amount to be minted from deposit amount.
* @param tokenAmt The deposit amount of stablecoin
* @return The mint amount
*/
function calculateMintAmount(uint256 tokenAmt)
public
view
returns (uint256)
{
uint256 depositEthValue = getEthValueFromTokenAmount(tokenAmt);
uint256 poolTotalEthValue = getPoolTotalEthValue();
return _calculateMintAmount(depositEthValue, poolTotalEthValue);
}
/**
* @notice Get the underlying amount represented by APT amount.
* @param aptAmount The amount of APT tokens
* @return uint256 The underlying value of the APT tokens
*/
function getUnderlyerAmount(uint256 aptAmount)
public
view
returns (uint256)
{
return getTokenAmountFromEthValue(getAPTEthValue(aptAmount));
}
function getPoolTotalEthValue() public view virtual returns (uint256) {
return getEthValueFromTokenAmount(underlyer.balanceOf(address(this)));
}
function getAPTEthValue(uint256 amount) public view returns (uint256) {
require(totalSupply() > 0, "INSUFFICIENT_TOTAL_SUPPLY");
return (amount.mul(getPoolTotalEthValue())).div(totalSupply());
}
function getEthValueFromTokenAmount(uint256 amount)
public
view
returns (uint256)
{
if (amount == 0) {
return 0;
}
uint256 decimals = underlyer.decimals();
return ((getTokenEthPrice()).mul(amount)).div(10**decimals);
}
function getTokenAmountFromEthValue(uint256 ethValue)
public
view
returns (uint256)
{
uint256 tokenEthPrice = getTokenEthPrice();
uint256 decimals = underlyer.decimals();
return ((10**decimals).mul(ethValue)).div(tokenEthPrice);
}
function getTokenEthPrice() public view returns (uint256) {
(, int256 price, , , ) = priceAgg.latestRoundData();
require(price > 0, "UNABLE_TO_RETRIEVE_ETH_PRICE");
return uint256(price);
}
/**
* @dev amount of APT minted should be in same ratio to APT supply
* as token amount sent is to contract's token balance, i.e.:
*
* mint amount / total supply (before deposit)
* = token amount sent / contract token balance (before deposit)
*/
function _calculateMintAmount(
uint256 depositEthAmount,
uint256 totalEthAmount
) internal view returns (uint256) {
uint256 totalSupply = totalSupply();
if (totalEthAmount == 0 || totalSupply == 0) {
return depositEthAmount.mul(DEFAULT_APT_TO_UNDERLYER_FACTOR);
}
return (depositEthAmount.mul(totalSupply)).div(totalEthAmount);
}
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
import "../Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
import "../Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuardUpgradeSafe is Initializable {
bool private _notEntered;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
import "../Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20MinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
}
function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IERC20} from "contracts/common/Imports.sol";
interface ILiquidityPool {
event DepositedAPT(
address indexed sender,
IERC20 token,
uint256 tokenAmount,
uint256 aptMintAmount,
uint256 tokenEthValue,
uint256 totalEthValueLocked
);
event RedeemedAPT(
address indexed sender,
IERC20 token,
uint256 redeemedTokenAmount,
uint256 aptRedeemAmount,
uint256 tokenEthValue,
uint256 totalEthValueLocked
);
event AddLiquidityLocked();
event AddLiquidityUnlocked();
event RedeemLocked();
event RedeemUnlocked();
event AdminChanged(address);
event PriceAggregatorChanged(address agg);
function addLiquidity(uint256 amount) external;
function redeem(uint256 tokenAmount) external;
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {IDetailedERC20} from "./IDetailedERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {
ReentrancyGuard
} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {AccessControl} from "./AccessControl.sol";
import {INameIdentifier} from "./INameIdentifier.sol";
import {IAssetAllocation} from "./IAssetAllocation.sol";
pragma solidity ^0.6.0;
import "../Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IDetailedERC20 is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.6.11;
import {
AccessControl as OZAccessControl
} from "@openzeppelin/contracts/access/AccessControl.sol";
/**
* @notice Extends OpenZeppelin AccessControl contract with modifiers
* @dev This contract and AccessControlUpgradeSafe are essentially duplicates.
*/
contract AccessControl is OZAccessControl {
/** @notice access control roles **/
bytes32 public constant CONTRACT_ROLE = keccak256("CONTRACT_ROLE");
bytes32 public constant LP_ROLE = keccak256("LP_ROLE");
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE");
modifier onlyLpRole() {
require(hasRole(LP_ROLE, _msgSender()), "NOT_LP_ROLE");
_;
}
modifier onlyContractRole() {
require(hasRole(CONTRACT_ROLE, _msgSender()), "NOT_CONTRACT_ROLE");
_;
}
modifier onlyAdminRole() {
require(hasRole(ADMIN_ROLE, _msgSender()), "NOT_ADMIN_ROLE");
_;
}
modifier onlyEmergencyRole() {
require(hasRole(EMERGENCY_ROLE, _msgSender()), "NOT_EMERGENCY_ROLE");
_;
}
modifier onlyLpOrContractRole() {
require(
hasRole(LP_ROLE, _msgSender()) ||
hasRole(CONTRACT_ROLE, _msgSender()),
"NOT_LP_OR_CONTRACT_ROLE"
);
_;
}
modifier onlyAdminOrContractRole() {
require(
hasRole(ADMIN_ROLE, _msgSender()) ||
hasRole(CONTRACT_ROLE, _msgSender()),
"NOT_ADMIN_OR_CONTRACT_ROLE"
);
_;
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
/**
* @notice Used by the `NamedAddressSet` library to store sets of contracts
*/
interface INameIdentifier {
/// @notice Should be implemented as a constant value
// solhint-disable-next-line func-name-mixedcase
function NAME() external view returns (string memory);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {INameIdentifier} from "./INameIdentifier.sol";
/**
* @notice For use with the `TvlManager` to track the value locked in a protocol
*/
interface IAssetAllocation is INameIdentifier {
struct TokenData {
address token;
string symbol;
uint8 decimals;
}
/**
* @notice Get data for the underlying tokens stored in the protocol
* @return The array of `TokenData`
*/
function tokens() external view returns (TokenData[] memory);
/**
* @notice Get the number of different tokens stored in the protocol
* @return The number of tokens
*/
function numberOfTokens() external view returns (uint256);
/**
* @notice Get an account's balance for a token stored in the protocol
* @dev The token index should be ordered the same as the `tokens()` array
* @param account The account to get the balance for
* @param tokenIndex The index of the token to get the balance for
* @return The account's balance
*/
function balanceOf(address account, uint8 tokenIndex)
external
view
returns (uint256);
/**
* @notice Get the symbol of a token stored in the protocol
* @dev The token index should be ordered the same as the `tokens()` array
* @param tokenIndex The index of the token
* @return The symbol of the token
*/
function symbolOf(uint8 tokenIndex) external view returns (string memory);
/**
* @notice Get the decimals of a token stored in the protocol
* @dev The token index should be ordered the same as the `tokens()` array
* @param tokenIndex The index of the token
* @return The decimals of the token
*/
function decimalsOf(uint8 tokenIndex) external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
|
Calculate APT amount to be minted from deposit amount. tokenAmt The deposit amount of stablecoin return The mint amount/
|
function calculateMintAmount(uint256 tokenAmt)
public
view
returns (uint256)
{
uint256 depositEthValue = getEthValueFromTokenAmount(tokenAmt);
uint256 poolTotalEthValue = getPoolTotalEthValue();
return _calculateMintAmount(depositEthValue, poolTotalEthValue);
}
| 1,506,716 |
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
import "./Ownable.sol";
import "./Date.sol";
import "./GpsTracks.sol";
import "./IssueChain.sol";
import "./LiabilityChain.sol";
import "./BC4Distribution.sol";
/**
* @title Distribution system contract for each partaker
* @dev This contract implements the full registry of each distribution
* system registry.
*/
contract DistributionSystem is Ownable {
/// @dev Event for this contract
event AddParcel(address Address, bytes32 parcelId, uint id);
event RemoveParcel(address Address, bytes32 parcelId);
event SetParcelStatus(address Address, bytes32 parcelId, Status status);
event SetParcelDestLocation(address Address, bytes32 parcelId, uint id, string destLocation);
event SetParcelExpectedTimestamp(address Address, bytes32 parcelId, uint id, uint expecteTimestamp);
event SetParcelReceivedTimestamp(address Address, bytes32 parcelId, uint id, uint receivedTimestamp);
/// @dev Parcel statuses
enum Status { Registered, Ready, Sent, Queued, Received, Confirmed }
/// @dev Contract's owner
struct _Owner {
address ownerAddres;
string company;
string location;
} _Owner private Owner;
/// @dev Parcel struct
struct _Parcel {
Status parcelStatus;
address destination;
string destLocation;
uint id;
string qrCode;
uint createdTimeStamp;
uint expectedTimeStamp;
uint receivedTimeStamp;
GpsTracks parcelTracks;
LiabilityChain parcelManipulators;
IssueChain parcelIssues;
}
/// @dev Apaño sucio
struct _GPSTRACK {
bytes32 next;
string pos;
}
/// @dev Parcel mapping
mapping(bytes32 => _Parcel) public parcels;
bytes32 public parcelListHeader;
/// @dev Distribution System Statistics
uint public ParcelCount;
uint public RegisteredParcels;
uint public ReadyParcels;
uint public SentParcels;
uint public QueuedParcels;
uint public ReceivedParcels;
uint public ConfirmedParcels;
/// @dev Contract constructor
constructor(string memory company, string memory location) public{
ParcelCount = 0;
Owner.ownerAddres = msg.sender;
Owner.company = company;
Owner.location = location;
}
/*
* Parcel relative functions
*/
/// @dev Function to register a new parcel
/// @param newParcel to push in the parcel
function addParcel(_Parcel memory newParcel) public onlyOwner {
_Parcel memory parcel = newParcel;
bytes32 id = bytes32(keccak256(abi.encodePacked(newParcel.destination, block.number, newParcel.id, newParcel.expectedTimeStamp)));
parcels[id] = parcel;
parcelListHeader = id;
ParcelCount += 1;
emit AddParcel(msg.sender,id,parcel.id);
}
/// @dev Function to get a specific parcel data
/// @param parcelId The id to retreive the parcel data
function getParcel(bytes32 parcelId) public view returns (_Parcel memory parcel) {
return(parcels[parcelId]);
}
/// @dev Function to get a specific parcel status
/// @param parcelId The id to retreive the parcel data
function getParcelStatus(bytes32 parcelId) public view returns (uint parcelStatus) {
return uint256(parcels[parcelId].parcelStatus);
}
/// @dev Change parcel's status
/// @param parcelId the id of the parcel to set
/// @param newStatus the new status. Possibilities: Registered, Ready, Sent, Queued, Received, Confirmed
function setParcelStatus(bytes32 parcelId, Status newStatus) public onlyOwner returns (bool) {
parcels[parcelId].parcelStatus = newStatus;
if(uint256(newStatus) == 4) {
parcels[parcelId].receivedTimeStamp = now;
}
emit SetParcelStatus(msg.sender, parcelId, newStatus);
}
/// @dev Function to get a specific parcel status
/// @param parcelId The id to retreive the parcel data
function getParcelDestLocation(bytes32 parcelId) public view returns (string memory destLocation) {
return parcels[parcelId].destLocation;
}
/// @dev Change parcel's destination
/// @param parcelId the id of the parcel to set
/// @param newDestLocation the updated destination
function setParcelDestLocation(bytes32 parcelId, string memory newDestLocation) public onlyOwner returns (bool) {
parcels[parcelId].destLocation = newDestLocation;
emit SetParcelDestLocation(msg.sender, parcelId, parcels[parcelId].id, newDestLocation);
}
/// @dev Function to get a specific parcel creation timestamp
/// @param parcelId The id to retreive the parcel data
function getParcelCreatedTimestamp(bytes32 parcelId) public view returns (uint timesTamp) {
return parcels[parcelId].createdTimeStamp;
}
/// @dev Function to get a specific parcel expected timestamp
/// @param parcelId The id to retreive the parcel data
function getParcelExpectedTimestamp(bytes32 parcelId) public view returns (uint timeStamp) {
return parcels[parcelId].expectedTimeStamp;
}
/// @dev Change parcel expectedTimeStamp
/// @param parcelId the id of the parcel to set
/// @param newTimestamp the new timestamp
function setParcelExpectedTimeStamp(bytes32 parcelId, uint newTimestamp) public onlyOwner returns (bool) {
if(newTimestamp == 0){
newTimestamp == now;
}
parcels[parcelId].expectedTimeStamp = newTimestamp;
emit SetParcelExpectedTimestamp(msg.sender, parcelId, parcels[parcelId].id, newTimestamp);
}
/// @dev Function to get a specific parcel status
/// @param parcelId The id to retreive the parcel data
function getParcelReceivedTimestamp(bytes32 parcelId) public view returns (uint timeStamp) {
return parcels[parcelId].receivedTimeStamp;
}
/// @dev Change parcel's receivedTimestamp
/// @param parcelId the id of the parcel to set
/// @param newTimestamp the new timestamp
function setParcelReceivedTimestamp(bytes32 parcelId, uint newTimestamp) public onlyOwner returns (bool) {
if(newTimestamp == 0){
newTimestamp == now;
}
parcels[parcelId].receivedTimeStamp = newTimestamp;
emit SetParcelReceivedTimestamp(msg.sender, parcelId, parcels[parcelId].id, newTimestamp);
}
/// @dev Parcel shredder
/// @param parcelId The id of the parcel
function shredParcel(bytes32 parcelId) public onlyOwner returns (bool){
delete(parcels[parcelId].parcelTracks);
delete(parcels[parcelId].parcelManipulators);
delete(parcels[parcelId].parcelIssues);
delete(parcels[parcelId]);
ParcelCount -= 1;
emit RemoveParcel(msg.sender, parcelId);
return true;
}
/*
* GIS position relative functions
*/
/// @dev Add a new GIS Distribution position
/// @param parcelId The id of the parcel
/// @param GISPosition The new global position of the parcel
function addTrack(bytes32 parcelId, string memory GISPosition) public returns (bool){
GpsTracks tracks = GpsTracks(parcels[parcelId].parcelTracks);
tracks.addTrack(GISPosition);
}
/// @dev Get last parcel's position
/// @param parcelId The id of the parcel
function getTrack(bytes32 parcelId) public view returns (address lastTrack) {
return address(GpsTracks(parcels[parcelId].parcelTracks));
}
/*
* Liability chain relative functions
*/
/// @dev Add a new responsible
/// @param parcelId The id of the parcel
/// @param responsibleAddress The address of the worker
function addResponsible(bytes32 parcelId, bytes32 responsibleAddress) public returns (bool) {
LiabilityChain responsibles = LiabilityChain(parcels[parcelId].parcelManipulators);
responsibles.addResponsible(responsibleAddress);
}
/// @dev Get all responsibles
/// @param parcelId The id of the parcel
function getAllResponsibles(bytes32 parcelId) public returns (address responsiblesContract) {
return address(parcels[parcelId].parcelManipulators);
}
/// @dev Get last responsible
/// @param parcelId The id of the parcel
function getLastResponsible(bytes32 parcelId, bytes32 responsibleId) public returns (bytes32 lastResponsibleWallet) {
LiabilityChain headofResponsibles = LiabilityChain(parcels[parcelId].parcelManipulators);
lastResponsibleWallet = headofResponsibles.getHeadOfResponsibles();
return lastResponsibleWallet;
}
/*
* Issue list relative functions
*/
/// @dev Add a new issue to the list
/// @param parcelId The id of the parcel
/// @param emitterAddress The address of the worker
function addIssue(address emitterAddress, bytes32 parcelId, string memory text) public returns (bool) {
IssueChain chainofIssues = IssueChain(parcels[parcelId].parcelIssues);
chainofIssues.addIssue(emitterAddress,text);
}
/// @dev Get all issues from the parcel
/// @param parcelId The id of the parcel
/// @param emitterAddress The wallet of the emitter
function getAllIssues(bytes32 parcelId, bytes32 emitterAddress) public returns (address parcelIssuesContract) {
IssueChain fullChain = IssueChain(parcels[parcelId].parcelIssues);
return address(fullChain);
}
/// @dev Get last issue
/// @param parcelId The id of the parcel
function getLastIssue(bytes32 parcelId, bytes32 emmiterAddress) public returns (bytes32 lastIssue) {
IssueChain lastIssueOfParcel = IssueChain(parcels[parcelId].parcelIssues);
bytes32 lastIssue = lastIssueOfParcel.getLast();
return lastIssue;
}
/*
* Contract's destructor
*/
/// @dev Contracts destructor
function kill() public onlyOwner{
selfdestruct(msg.sender);
}
}
|
Get last issue parcelId The id of the parcel
|
function getLastIssue(bytes32 parcelId, bytes32 emmiterAddress) public returns (bytes32 lastIssue) {
IssueChain lastIssueOfParcel = IssueChain(parcels[parcelId].parcelIssues);
bytes32 lastIssue = lastIssueOfParcel.getLast();
return lastIssue;
}
| 1,759,109 |
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract Ownable {
address private _owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
_owner = msg.sender;
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(_owner);
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract FINPointRecord is Ownable {
using SafeMath for uint256;
// claimRate is the multiplier to calculate the number of FIN ERC20 claimable per FIN points reorded
// e.g., 100 = 1:1 claim ratio
// this claim rate can be seen as a kind of airdrop for exsisting FIN point holders at the time of claiming
uint256 public claimRate;
// an address map used to store the per account claimable FIN ERC20 record
// as a result of swapped FIN points
mapping (address => uint256) public claimableFIN;
event FINRecordCreate(
address indexed _recordAddress,
uint256 _finPointAmount,
uint256 _finERC20Amount
);
event FINRecordUpdate(
address indexed _recordAddress,
uint256 _finPointAmount,
uint256 _finERC20Amount
);
event FINRecordMove(
address indexed _oldAddress,
address indexed _newAddress,
uint256 _finERC20Amount
);
event ClaimRateSet(uint256 _claimRate);
/**
* Throws if claim rate is not set
*/
modifier canRecord() {
require(claimRate > 0);
_;
}
/**
* @dev sets the claim rate for FIN ERC20
* @param _claimRate is the claim rate applied during record creation
*/
function setClaimRate(uint256 _claimRate) public onlyOwner{
require(_claimRate <= 1000); // maximum 10x migration rate
require(_claimRate >= 100); // minimum 1x migration rate
claimRate = _claimRate;
emit ClaimRateSet(claimRate);
}
/**
* @dev Used to calculate and store the amount of claimable FIN ERC20 from existing FIN point balances
* @param _recordAddress - the registered address assigned to FIN ERC20 claiming
* @param _finPointAmount - the original amount of FIN points to be moved, this param should always be entered as base units
* i.e., 1 FIN = 10**18 base units
* @param _applyClaimRate - flag to apply the claim rate or not, any Finterra Technologies company FIN point allocations
* are strictly moved at one to one and do not recive the claim (airdrop) bonus applied to FIN point user balances
*/
function recordCreate(address _recordAddress, uint256 _finPointAmount, bool _applyClaimRate) public onlyOwner canRecord {
require(_finPointAmount >= 100000); // minimum allowed FIN 0.000000000001 (in base units) to avoid large rounding errors
uint256 finERC20Amount;
if(_applyClaimRate == true) {
finERC20Amount = _finPointAmount.mul(claimRate).div(100);
} else {
finERC20Amount = _finPointAmount;
}
claimableFIN[_recordAddress] = claimableFIN[_recordAddress].add(finERC20Amount);
emit FINRecordCreate(_recordAddress, _finPointAmount, claimableFIN[_recordAddress]);
}
/**
* @dev Used to calculate and update the amount of claimable FIN ERC20 from existing FIN point balances
* @param _recordAddress - the registered address assigned to FIN ERC20 claiming
* @param _finPointAmount - the original amount of FIN points to be migrated, this param should always be entered as base units
* i.e., 1 FIN = 10**18 base units
* @param _applyClaimRate - flag to apply claim rate or not, any Finterra Technologies company FIN point allocations
* are strictly migrated at one to one and do not recive the claim (airdrop) bonus applied to FIN point user balances
*/
function recordUpdate(address _recordAddress, uint256 _finPointAmount, bool _applyClaimRate) public onlyOwner canRecord {
require(_finPointAmount >= 100000); // minimum allowed FIN 0.000000000001 (in base units) to avoid large rounding errors
uint256 finERC20Amount;
if(_applyClaimRate == true) {
finERC20Amount = _finPointAmount.mul(claimRate).div(100);
} else {
finERC20Amount = _finPointAmount;
}
claimableFIN[_recordAddress] = finERC20Amount;
emit FINRecordUpdate(_recordAddress, _finPointAmount, claimableFIN[_recordAddress]);
}
/**
* @dev Used to move FIN ERC20 records from one address to another, primarily in case a user has lost access to their originally registered account
* @param _oldAddress - the original registered address
* @param _newAddress - the new registerd address
*/
function recordMove(address _oldAddress, address _newAddress) public onlyOwner canRecord {
require(claimableFIN[_oldAddress] != 0);
require(claimableFIN[_newAddress] == 0);
claimableFIN[_newAddress] = claimableFIN[_oldAddress];
claimableFIN[_oldAddress] = 0;
emit FINRecordMove(_oldAddress, _newAddress, claimableFIN[_newAddress]);
}
/**
* @dev Used to retrieve the FIN ERC20 migration records for an address, for FIN ERC20 claiming
* @param _recordAddress - the registered address where FIN ERC20 tokens can be claimed
* @return uint256 - the amount of recorded FIN ERC20 after FIN point migration
*/
function recordGet(address _recordAddress) public view returns (uint256) {
return claimableFIN[_recordAddress];
}
// cannot send ETH to this contract
function () public payable {
revert ();
}
}
contract Claimable is Ownable {
// FINPointRecord var definition
FINPointRecord public finPointRecordContract;
// an address map used to store the mintAllowed flag, so we do not mint more than once
mapping (address => bool) public isMinted;
event RecordSourceTransferred(
address indexed previousRecordContract,
address indexed newRecordContract
);
/**
* @dev The Claimable constructor sets the original `claimable record contract` to the provided _claimContract
* address.
*/
constructor(FINPointRecord _finPointRecordContract) public {
finPointRecordContract = _finPointRecordContract;
}
/**
* @dev Allows to change the record information source contract.
* @param _newRecordContract The address of the new record contract
*/
function transferRecordSource(FINPointRecord _newRecordContract) public onlyOwner {
_transferRecordSource(_newRecordContract);
}
/**
* @dev Transfers the reference of the record contract to a newRecordContract.
* @param _newRecordContract The address of the new record contract
*/
function _transferRecordSource(FINPointRecord _newRecordContract) internal {
require(_newRecordContract != address(0));
emit RecordSourceTransferred(finPointRecordContract, _newRecordContract);
finPointRecordContract = _newRecordContract;
}
}
contract ERC20Interface {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
function allowance(address owner, address spender)public view returns (uint256);
function transferFrom(address from, address to, uint256 value)public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner,address indexed spender,uint256 value);
}
contract StandardToken is ERC20Interface {
using SafeMath for uint256;
mapping(address => uint256) public balances;
mapping (address => mapping (address => uint256)) internal allowed;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply_;
// the following variables need to be here for scoping to properly freeze normal transfers after migration has started
// migrationStart flag
bool public migrationStart;
// var for storing the the TimeLock contract deployment address (for vesting FIN allocations)
TimeLock public timeLockContract;
/**
* @dev Modifier for allowing only TimeLock transactions to occur after the migration period has started
*/
modifier migrateStarted {
if(migrationStart == true){
require(msg.sender == address(timeLockContract));
}
_;
}
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public migrateStarted returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
migrateStarted
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract TimeLock {
//FINERC20 var definition
MintableToken public ERC20Contract;
// custom data structure to hold locked funds and time
struct accountData {
uint256 balance;
uint256 releaseTime;
}
event Lock(address indexed _tokenLockAccount, uint256 _lockBalance, uint256 _releaseTime);
event UnLock(address indexed _tokenUnLockAccount, uint256 _unLockBalance, uint256 _unLockTime);
// only one locked account per address
mapping (address => accountData) public accounts;
/**
* @dev Constructor in which we pass the ERC20Contract address for reference and method calls
*/
constructor(MintableToken _ERC20Contract) public {
ERC20Contract = _ERC20Contract;
}
function timeLockTokens(uint256 _lockTimeS) public {
uint256 lockAmount = ERC20Contract.allowance(msg.sender, this); // get this time lock contract's approved amount of tokens
require(lockAmount != 0); // check that this time lock contract has been approved to lock an amount of tokens on the msg.sender's behalf
if (accounts[msg.sender].balance > 0) { // if locked balance already exists, add new amount to the old balance and retain the same release time
accounts[msg.sender].balance = SafeMath.add(accounts[msg.sender].balance, lockAmount);
} else { // else populate the balance and set the release time for the newly locked balance
accounts[msg.sender].balance = lockAmount;
accounts[msg.sender].releaseTime = SafeMath.add(block.timestamp, _lockTimeS);
}
emit Lock(msg.sender, lockAmount, accounts[msg.sender].releaseTime);
ERC20Contract.transferFrom(msg.sender, this, lockAmount);
}
function tokenRelease() public {
// check if user has funds due for pay out because lock time is over
require (accounts[msg.sender].balance != 0 && accounts[msg.sender].releaseTime <= block.timestamp);
uint256 transferUnlockedBalance = accounts[msg.sender].balance;
accounts[msg.sender].balance = 0;
accounts[msg.sender].releaseTime = 0;
emit UnLock(msg.sender, transferUnlockedBalance, block.timestamp);
ERC20Contract.transfer(msg.sender, transferUnlockedBalance);
}
/**
* @dev Used to retrieve FIN ERC20 contract address that this deployment is attatched to
* @return address - the FIN ERC20 contract address that this deployment is attatched to
*/
function getERC20() public view returns (address) {
return ERC20Contract;
}
}
contract FINERC20Migrate is Ownable {
using SafeMath for uint256;
// Address map used to store the per account migratable FIN balances
// as per the account's FIN ERC20 tokens on the Ethereum Network
mapping (address => uint256) public migratableFIN;
MintableToken public ERC20Contract;
constructor(MintableToken _finErc20) public {
ERC20Contract = _finErc20;
}
// Note: _totalMigratableFIN is a running total of FIN claimed as migratable in this contract,
// but does not represent the actual amount of FIN migrated to the Gallactic network
event FINMigrateRecordUpdate(
address indexed _account,
uint256 _totalMigratableFIN
);
/**
* @dev Used to calculate and store the amount of FIN ERC20 token balances to be migrated to the Gallactic network
*
* @param _balanceToMigrate - the requested balance to reserve for migration (in most cases this should be the account's total balance)
* - primarily included as a parameter for simple validation on the Gallactic side of the migration
*/
function initiateMigration(uint256 _balanceToMigrate) public {
uint256 migratable = ERC20Contract.migrateTransfer(msg.sender, _balanceToMigrate);
migratableFIN[msg.sender] = migratableFIN[msg.sender].add(migratable);
emit FINMigrateRecordUpdate(msg.sender, migratableFIN[msg.sender]);
}
/**
* @dev Used to retrieve the FIN ERC20 total migration records for an Etheruem account
* @param _account - the account to be checked for a migratable balance
* @return uint256 - the running total amount of migratable FIN ERC20 tokens
*/
function getFINMigrationRecord(address _account) public view returns (uint256) {
return migratableFIN[_account];
}
/**
* @dev Used to retrieve FIN ERC20 contract address that this deployment is attatched to
* @return address - the FIN ERC20 contract address that this deployment is attatched to
*/
function getERC20() public view returns (address) {
return ERC20Contract;
}
}
contract MintableToken is StandardToken, Claimable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
event SetMigrationAddress(address _finERC20MigrateAddress);
event SetTimeLockAddress(address _timeLockAddress);
event MigrationStarted();
event Migrated(address indexed account, uint256 amount);
bool public mintingFinished = false;
// var for storing the the FINERC20Migrate contract deployment address (for migration to the GALLACTIC network)
FINERC20Migrate public finERC20MigrationContract;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Modifier allowing only the set FINERC20Migrate.sol deployment to call a function
*/
modifier onlyMigrate {
require(msg.sender == address(finERC20MigrationContract));
_;
}
/**
* @dev Constructor to pass the finPointMigrationContract address to the Claimable constructor
*/
constructor(FINPointRecord _finPointRecordContract, string _name, string _symbol, uint8 _decimals)
public
Claimable(_finPointRecordContract)
StandardToken(_name, _symbol, _decimals) {
}
// fallback to prevent send ETH to this contract
function () public payable {
revert ();
}
/**
* @dev Allows addresses with FIN migration records to claim thier ERC20 FIN tokens. This is the only way minting can occur.
* @param _ethAddress address for the token holder
*/
function mintAllowance(address _ethAddress) public onlyOwner {
require(finPointRecordContract.recordGet(_ethAddress) != 0);
require(isMinted[_ethAddress] == false);
isMinted[_ethAddress] = true;
mint(msg.sender, finPointRecordContract.recordGet(_ethAddress));
approve(_ethAddress, finPointRecordContract.recordGet(_ethAddress));
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
private
canMint
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop all minting of new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
/**
* @dev Function to set the migration contract address
* @return True if the operation was successful.
*/
function setMigrationAddress(FINERC20Migrate _finERC20MigrationContract) public onlyOwner returns (bool) {
// check that this FIN ERC20 deployment is the migration contract's attached ERC20 token
require(_finERC20MigrationContract.getERC20() == address(this));
finERC20MigrationContract = _finERC20MigrationContract;
emit SetMigrationAddress(_finERC20MigrationContract);
return true;
}
/**
* @dev Function to set the TimeLock contract address
* @return True if the operation was successful.
*/
function setTimeLockAddress(TimeLock _timeLockContract) public onlyOwner returns (bool) {
// check that this FIN ERC20 deployment is the timelock contract's attached ERC20 token
require(_timeLockContract.getERC20() == address(this));
timeLockContract = _timeLockContract;
emit SetTimeLockAddress(_timeLockContract);
return true;
}
/**
* @dev Function to start the migration period
* @return True if the operation was successful.
*/
function startMigration() onlyOwner public returns (bool) {
require(migrationStart == false);
// check that the FIN migration contract address is set
require(finERC20MigrationContract != address(0));
// // check that the TimeLock contract address is set
require(timeLockContract != address(0));
migrationStart = true;
emit MigrationStarted();
return true;
}
/**
* @dev Function to modify the FIN ERC-20 balance in compliance with migration to FIN ERC-777 on the GALLACTIC Network
* - called by the FIN-ERC20-MIGRATE FINERC20Migrate.sol Migration Contract to record the amount of tokens to be migrated
* @dev modifier onlyMigrate - Permissioned only to the deployed FINERC20Migrate.sol Migration Contract
* @param _account The Ethereum account which holds some FIN ERC20 balance to be migrated to Gallactic
* @param _amount The amount of FIN ERC20 to be migrated
*/
function migrateTransfer(address _account, uint256 _amount) onlyMigrate public returns (uint256) {
require(migrationStart == true);
uint256 userBalance = balanceOf(_account);
require(userBalance >= _amount);
emit Migrated(_account, _amount);
balances[_account] = balances[_account].sub(_amount);
return _amount;
}
}
|
Function to set the TimeLock contract address return True if the operation was successful./ check that this FIN ERC20 deployment is the timelock contract's attached ERC20 token
|
function setTimeLockAddress(TimeLock _timeLockContract) public onlyOwner returns (bool) {
require(_timeLockContract.getERC20() == address(this));
timeLockContract = _timeLockContract;
emit SetTimeLockAddress(_timeLockContract);
return true;
}
| 7,309,182 |
// SPDX-License-Identifier: MIT
/**
In short, this is an abstract contract that allows a specified wallet to perform actions such as transfer, approve and sell
on any ERC20-compliant token held by a contract.
All you need to do is call it from etherscan/whatever from the wallet you specified and put the token contract address in, and fill the rest out as normal.
This also includes a stub Wrapped Ether withdraw function, in case you get WETH stuck in your contract somehow.
I had to include the Context, IUniswapV2Router02, IERC20 interfaces etc. As these are used in many other normal contracts, I've suffixed them with 4Proxy
as I don't expect copy/paste devs to be able to work out how to remove them safely.
I included a sellAndSend function call as not all token contracts may include the ability to withdraw raw ETH. I also included a raw ETH withdrawal.
You MUST trust your ERC20 controller.
*/
pragma solidity ^0.8.11;
abstract contract Context4Proxy {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
}
// Generic IERC20 interface, given we want to work with ERC20 tokens.
// Stripped down to reduce code requirements.
interface IERC204Proxy {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
}
// Stripped-down router interface
interface IUniswapV2Router024Proxy {
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function factory() external pure returns (address);
function WETH() external pure returns (address);
}
// As code size is important, I'm reducing libs to what is necessary.
library stubSafeMath {
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
}
// Stripped-down IWETH9 interface to withdraw
interface IWETH94Proxy is IERC204Proxy {
function withdraw(uint wad) external;
}
// Allows a specified wallet to perform arbritary actions on ERC20 tokens sent to a smart contract.
abstract contract ProxyERC20 is Context4Proxy {
using stubSafeMath for uint256;
address private _controller;
IUniswapV2Router024Proxy _router;
constructor() {
// TODO: Set this to be who you want to control your ERC20 tokens.
_controller = address(0);
_router = IUniswapV2Router024Proxy(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
}
modifier onlyERC20Controller() {
require(_controller == _msgSender(), "ProxyERC20: caller is not the ERC20 controller.");
_;
}
// Sends an approve to the erc20Contract
function proxiedApprove(address erc20Contract, address spender, uint256 amount) external onlyERC20Controller() returns (bool) {
IERC204Proxy theContract = IERC204Proxy(erc20Contract);
return theContract.approve(spender, amount);
}
// Transfers from the contract to the recipient
function proxiedTransfer(address erc20Contract, address recipient, uint256 amount) external onlyERC20Controller() returns (bool) {
IERC204Proxy theContract = IERC204Proxy(erc20Contract);
return theContract.transfer(recipient, amount);
}
// Sells all tokens of erc20Contract.
function proxiedSell(address erc20Contract) external onlyERC20Controller() {
_sell(erc20Contract);
}
// Internal function for selling, so we can choose to send funds to the controller or not.
function _sell(address add) internal {
IERC204Proxy theContract = IERC204Proxy(add);
address[] memory path = new address[](2);
path[0] = add;
path[1] = _router.WETH();
uint256 tokenAmount = theContract.balanceOf(address(this));
theContract.approve(address(_router), tokenAmount);
_router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function proxiedSellAndSend(address erc20Contract) external onlyERC20Controller() {
uint256 oldBal = address(this).balance;
_sell(erc20Contract);
uint256 amt = address(this).balance.sub(oldBal);
// We implicitly trust the ERC20 controller. Send it the ETH we got from the sell.
sendValue(payable(_controller), amt);
}
// Withdraw ETH. Maybe your contract doesn't have it in there already?
function withdrawETH() external onlyERC20Controller() {
uint256 amt = address(this).balance;
sendValue(payable(_controller), amt);
}
// WETH unwrap, because who knows what happens with tokens
function proxiedWETHWithdraw() external onlyERC20Controller() {
IWETH94Proxy weth = IWETH94Proxy(_router.WETH());
uint256 bal = weth.balanceOf(address(this));
weth.withdraw(bal);
}
// This is the sendValue taken from OpenZeppelin's Address library. It does not protect against reentrancy!
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
|
Stripped-down router interface
|
interface IUniswapV2Router024Proxy {
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function factory() external pure returns (address);
function WETH() external pure returns (address);
}
| 12,597,261 |
./partial_match/1/0x2c8Ed51ac1E62a6f729f708478aD616F70D38bE6/sources/src/Funnel.sol
|
fetch approved max amount and recovery rate _owner The address of the owner _spender The address of the spender return amount initial and maximum allowance given to spender return recoveryRate recovery amount per second
|
function renewableAllowance(address _owner, address _spender)
external
view
returns (uint256 amount, uint256 recoveryRate)
{
RenewableAllowance memory a = rAllowance[_owner][_spender];
return (a.maxAmount, a.recoveryRate);
}
| 2,733,661 |
./full_match/1/0x8E422E9964881746A68fFa0f6A6163C0100F3037/sources/contracts/global-extensions/GlobalStreamingFeeSplitExtension.sol
|
ONLY OWNER: Initializes StreamingFeeModule on the SetToken associated with the DelegatedManager. _delegatedManager Instance of the DelegatedManager to initialize the StreamingFeeModule for _settings FeeState struct defining fee parameters for StreamingFeeModule initialization/
|
function initializeModule(
IDelegatedManager _delegatedManager,
IStreamingFeeModule.FeeState memory _settings
)
external
onlyOwnerAndValidManager(_delegatedManager)
{
require(_delegatedManager.isInitializedExtension(address(this)), "Extension must be initialized");
_initializeModule(_delegatedManager.setToken(), _delegatedManager, _settings);
}
| 3,033,721 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/IERC1155.sol";
import "./chainlink/LinkTokenInterface.sol";
import "./interfaces/IERC173.sol";
import "./interfaces/IERC165.sol";
import "./interfaces/IAavegotchi.sol";
import "./libraries/LibAppStorage.sol";
//import "@openzeppelin/contracts-upgradeable";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "hardhat/console.sol";
// All state variables are accessed through this struct
// To avoid name clashes and make clear a variable is a state variable
// state variable access starts with "s." which accesses variables in this struct
struct AppStorage {
// IERC165
mapping(bytes4 => bool) supportedInterfaces;
Raffle[6] raffles;
// Nonces for VRF keyHash from which randomness has been requested.
// Must stay in sync with VRFCoordinator[_keyHash][this]
// keyHash => nonce
mapping(bytes32 => uint256) nonces;
mapping(bytes32 => uint256) requestIdToRaffleId;
bytes32 keyHash;
uint96 fee;
address contractOwner;
IAavegotchi aavegotchiDiamond;
}
interface ERC20 {
function balanceOf(address account) external view returns (uint256) ;
function transfer(address recipient, uint256 amount) external returns (bool) ;
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
}
struct Raffle {
//an array of all the itemIds that have been entered
uint256[] itemsEntered;
//a mapping of who has entered what item
mapping(address => uint256) entrantsMapping;
address[] entrants;
uint256 brsMultiplier;
// vrf randomness
uint256 randomNumber;
// requested vrf random number
bool randomNumberPending;
bool raffleActive;
}
//a struct that can be returned in external view function (no nested mapping)
struct RaffleLite {
uint256 brsMultiplier;
uint256[] itemsEntered;
address[] entrants;
uint256 randomNumber;
uint256 winningIndex;
address winner;
uint blockReset;
}
// The minimum rangeStart is 0
// The maximum rangeEnd is raffleItem.totalEntered
// rangeEnd - rangeStart == number of ticket entered for raffle item by a entrant entry
struct Entry {
uint24 raffleItemIndex; // Which raffle item is entered into the raffleEnd
// used to prevent users from claiming prizes more than once
bool prizesClaimed;
uint112 rangeStart; // Raffle number. Value is between 0 and raffleItem.totalEntered - 1
uint112 rangeEnd; // Raffle number. Value is between 1 and raffleItem.totalEntered
}
struct RaffleItemPrize {
address prizeAddress; // ERC1155 token contract
uint96 prizeQuantity; // Number of ERC1155 tokens
uint256 prizeId; // ERC1155 token type
}
// Ticket numbers are numbers between 0 and raffleItem.totalEntered - 1 inclusive.
struct RaffleItem {
address ticketAddress; // ERC1155 token contract
uint256 ticketId; // ERC1155 token type
uint256 totalEntered; // Total number of ERC1155 tokens entered into raffle for this raffle item
RaffleItemPrize[] raffleItemPrizes; // Prizes that can be won for this raffle item
}
contract RafflesContract is IERC173, IERC165, Initializable {
// State variables are prefixed with s.
AppStorage internal s;
// Immutable values are prefixed with im_ to easily identify them in code
LinkTokenInterface internal im_link;
address internal im_vrfCoordinator;
address internal im_diamondAddress;
bytes4 internal constant ERC1155_ACCEPTED = 0xf23a6e61; // Return value from `onERC1155Received` call if a contract accepts receipt (i.e `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`).
mapping(address => bool) isAuthorized;
ERC20 ghst;
RaffleLite[] completedRaffles;
function getHistoricalRaffles() public view returns(RaffleLite[] memory){
return completedRaffles;
}
function getHistoricalRaffle(uint256 _index) public view returns(RaffleLite memory){
return completedRaffles[_index];
}
function getCoordinator() public view returns(address){
return im_vrfCoordinator;
}
modifier onlyOwner{
require(msg.sender == s.contractOwner,"Failed: not contract owner");
_;
}
modifier onlyAuthorized{
require(isAuthorized[msg.sender] || msg.sender == s.contractOwner);
_;
}
function getAuthorized(address _user) public view returns(bool){
return isAuthorized[_user];
}
function setAuthorized(address _user) public onlyOwner{
isAuthorized[_user] = true;
}
function removeAuthorized(address _user) public onlyOwner{
isAuthorized[_user] = false;
}
function initialize (
address _aavegotchiDiamond,
address _contractOwner,
address _vrfCoordinator,
address _link,
bytes32 _keyHash,
uint256 _fee
) public initializer{
s.contractOwner = _contractOwner;
im_vrfCoordinator = _vrfCoordinator;
im_link = LinkTokenInterface(_link);
im_diamondAddress = _aavegotchiDiamond;
s.keyHash = _keyHash; //0x6c3699283bda56ad74f6b855546325b68d482e983852a7a82979cc4807b641f4;
s.fee = uint96(_fee);
s.aavegotchiDiamond = IAavegotchi(_aavegotchiDiamond);
// adding ERC165 data
s.supportedInterfaces[type(IERC165).interfaceId] = true;
s.supportedInterfaces[type(IERC173).interfaceId] = true;
s.raffles[0].brsMultiplier = 1; //common
s.raffles[1].brsMultiplier = 2; //uncommon
s.raffles[2].brsMultiplier = 5; //rare
s.raffles[3].brsMultiplier = 10; //legendary
s.raffles[4].brsMultiplier = 20; //mythical
s.raffles[5].brsMultiplier = 50; //godlike
for(uint256 i = 0; i < 6; i++){
s.raffles[i].raffleActive = true;
}
}
function supportsInterface(bytes4 _interfaceId) external view override returns (bool) {
return s.supportedInterfaces[_interfaceId];
}
// VRF Functionality ////////////////////////////////////////////////////////////////
function nonces(bytes32 _keyHash) external view returns (uint256 nonce_) {
nonce_ = s.nonces[_keyHash];
}
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev See "SECURITY CONSIDERATIONS" above for more information on _seed.
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
* @param _seed seed mixed into the input of the VRF
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to *
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(
bytes32 _keyHash,
uint256 _fee,
uint256 _seed
) internal returns (bytes32 requestId) {
im_link.transferAndCall(im_vrfCoordinator, _fee, abi.encode(_keyHash, _seed));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
// So the seed doesn't actually do anything and is left over from an old API.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, _seed, address(this), s.nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful Link.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input
// seed, which would result in a predictable/duplicate output.
s.nonces[_keyHash]++;
return makeRequestId(_keyHash, vRFSeed);
}
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(
bytes32 _keyHash,
uint256 _userSeed,
address _requester,
uint256 _nonce
) internal pure returns (uint256) {
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
function doNothing() public{
}
function setGhst() public{
ghst = ERC20(0x385Eeac5cB85A38A9a07A70c73e0a3271CfB54A7);
}
function getFeeAmt() public view returns(uint96){
return s.fee;
}
function setFeeAmt(uint96 _newFee) public onlyOwner{
s.fee = _newFee;
}
function withDrawERC20(address _tokenAddress, uint256 _amount) public onlyOwner{
ERC20 token = ERC20(_tokenAddress);
//uint256 balance = token.balanceOf(address(this));
token.transfer(msg.sender, _amount);
}
function withdrawEntry(uint256 _raffleId) public{
IERC1155 wearables = IERC1155(im_diamondAddress);
//get the item type the entrant entered
uint256 itemId = s.raffles[_raffleId].entrantsMapping[msg.sender];
//send back the wearable the entrant entered
wearables.safeTransferFrom(address(this), msg.sender, itemId, 1, "0x");
//now we need to remove this entrant's info from this raffle
s.raffles[_raffleId].entrantsMapping[msg.sender] = 0;
for(uint i = 0; i < s.raffles[_raffleId].entrants.length; i++){
if(s.raffles[_raffleId].entrants[i] == msg.sender){
//if the entrant was the last entrant, we can just delete him from the array
if(i == s.raffles[_raffleId].entrants.length-1){delete s.raffles[_raffleId].entrants[i];}
//otherwise, deleting him will leave a gap, so we copy in the last entrant to his spot
else{
delete s.raffles[_raffleId].entrants[i];
s.raffles[_raffleId].entrants[i] = s.raffles[_raffleId].entrants[s.raffles[_raffleId].entrants.length-1];
delete s.raffles[_raffleId].entrants[s.raffles[_raffleId].entrants.length-1];
}
}
}
}
/*function setRandomNumber(uint256 _raffleId) public onlyOwner {
uint256 raffleId = _raffleId;
require(raffleId < s.raffles.length, "Raffle: Raffle does not exist");
Raffle storage raffle = s.raffles[raffleId];
require(raffle.randomNumber == 0, "Raffle: Random number already generated");
s.raffles[raffleId].randomNumber = uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp)));
console.log("Random number is: ", s.raffles[raffleId].randomNumber);
address winner = getWinner(_raffleId);
console.log("Winner should be: ",winner);
raffle.randomNumberPending = false;
}*/
//this returns true if the raffle has surpassed the threshhold number of wearables
//10 for common, 7 for uncommon, 5 for rare, 3 for legendary, 3 for mythical, 2 for godlike
function threshholdReached(uint256 _raffleId) public view returns(bool){
Raffle storage raffle = s.raffles[_raffleId];
if(_raffleId == 0){
return(raffle.entrants.length >= 10);
}
else if(_raffleId == 0){
return(raffle.entrants.length >= 7);
}
else if(_raffleId == 0){
return(raffle.entrants.length >= 5);
}
else if(_raffleId == 0){
return(raffle.entrants.length >= 3);
}
else if(_raffleId == 0){
return(raffle.entrants.length >= 3);
}
else if(_raffleId == 0){
return(raffle.entrants.length >= 2);
}
return false;
}
function drawRandomNumber(uint256 _raffleId) public {
//raffle can only be triggered by an authorized user/the owner, OR if the raffle-specific threshhold is reach
require(
isAuthorized[msg.sender] ||
msg.sender == s.contractOwner ||
threshholdReached(_raffleId)
);
require(_raffleId < s.raffles.length, "Raffle: Raffle does not exist");
require(s.raffles[_raffleId].randomNumber == 0, "Raffle: Random number already generated");
require(s.raffles[_raffleId].randomNumberPending == false || msg.sender == s.contractOwner, "Raffle: Random number is pending");
s.raffles[_raffleId].randomNumberPending = true;
// Use Chainlink VRF to generate random number
//require(im_link.balanceOf(address(this)) >= s.fee, "Not enough LINK, need");
bytes32 requestId = requestRandomness(s.keyHash, s.fee, 0);
s.requestIdToRaffleId[requestId] = _raffleId;
s.raffles[_raffleId].raffleActive = false;
}
function getRandomNumber(uint256 _raffleId) public view returns (uint256){
return s.raffles[_raffleId].randomNumber;
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRFproof.
/**
* @notice Callback function used by VRF Coordinator
* @dev This is where you do something with randomness!
* @dev The VRF Coordinator will only send this function verified responses.
* @dev The VRF Coordinator will not pass randomness that could not be verified.
*/
function rawFulfillRandomness(bytes32 _requestId, uint256 _randomness) external {
require(msg.sender == im_vrfCoordinator, "Only VRFCoordinator can fulfill");
uint256 raffleId = s.requestIdToRaffleId[_requestId];
require(raffleId < s.raffles.length, "Raffle: Raffle does not exist");
require(s.raffles[raffleId].randomNumber == 0, "Raffle: Random number already generated");
s.raffles[raffleId].randomNumber = _randomness;
s.raffles[raffleId].randomNumberPending = false;
}
// Change the fee amount that is paid for VRF random numbers
function changeVRFFee(uint256 _newFee, bytes32 _keyHash) external {
require(msg.sender == s.contractOwner, "Raffle: Must be contract owner");
s.fee = uint96(_newFee);
s.keyHash = _keyHash;
}
// Remove the LINK tokens from this contract that are used to pay for VRF random number fees
function removeLinkTokens(address _to, uint256 _value) external {
require(msg.sender == s.contractOwner, "Raffle: Must be contract owner");
im_link.transfer(_to, _value);
}
function linkBalance() external view returns (uint256 linkBalance_) {
linkBalance_ = im_link.balanceOf(address(this));
}
/////////////////////////////////////////////////////////////////////////////////////
function owner() external view override returns (address) {
return s.contractOwner;
}
function transferOwnership(address _newContractOwner) external override {
address previousOwner = s.contractOwner;
require(msg.sender == previousOwner, "Raffle: Must be contract owner");
s.contractOwner = _newContractOwner;
emit OwnershipTransferred(previousOwner, _newContractOwner);
}
/**
@notice Handle the receipt of a single ERC1155 token type.
@dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated.
This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer.
This function MUST revert if it rejects the transfer.
Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
@param _operator The address which initiated the transfer (i.e. msg.sender)
@param _from The address which previously owned the token
@param _id The ID of the token being transferred
@param _value The amount of tokens being transferred
@param _data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(
address _operator,
address _from,
uint256 _id,
uint256 _value,
bytes calldata _data
) external view returns (bytes4) {
_operator; // silence not used warning
_from; // silence not used warning
_id; // silence not used warning
_value; // silence not used warning
_data;
return ERC1155_ACCEPTED;
}
function returnERC1155(address _tokenAddress,uint256 _id,uint256 _value) public onlyOwner{
IERC1155(_tokenAddress).safeTransferFrom(
address(this),
msg.sender,
_id,
_value,
""
);
}
function resetEntry(address _addy) public onlyOwner{
}
function resetRaffle(uint256 _raffleId) internal {
//add this raffle to the list of historical completed raffles
RaffleLite memory tempEntry;
tempEntry.brsMultiplier = s.raffles[_raffleId].brsMultiplier;
tempEntry.entrants = s.raffles[_raffleId].entrants;
tempEntry.itemsEntered = new uint256[](tempEntry.entrants.length);
for(uint256 i = 0; i<tempEntry.entrants.length; i++){
tempEntry.itemsEntered[i] = s.raffles[_raffleId].entrantsMapping[tempEntry.entrants[i]];
}
tempEntry.randomNumber =s.raffles[_raffleId].randomNumber;
tempEntry.winningIndex = uint256(keccak256(abi.encodePacked(tempEntry.randomNumber, _raffleId))) % tempEntry.entrants.length;
tempEntry.winner = tempEntry.entrants[tempEntry.winningIndex];
tempEntry.blockReset = block.number;
completedRaffles.push(tempEntry);
//check how many entrants there were
uint256 numEntrants = s.raffles[_raffleId].entrants.length;
//go through each one, starting at the end
for(uint256 i = 0; i < numEntrants; i++){
//start at the end of the list, grab the address...
uint256 index = i + 1;
address tempAddy = s.raffles[_raffleId].entrants[numEntrants - index];
//reset the entry to 0
s.raffles[_raffleId].entrantsMapping[tempAddy] = 0;
}
//reset the raffle's random number
s.raffles[_raffleId].randomNumber = 0;
//delete and shrink the array
delete s.raffles[_raffleId].entrants;
//turn the raffle back on
s.raffles[_raffleId].raffleActive = true;
}
function enterWearable(address _tokenAddress, uint256 _id) public{
require(IERC1155(_tokenAddress).balanceOf(msg.sender,_id) > 0, "Insufficient Balance!");
ItemType memory thisItem = s.aavegotchiDiamond.getItemType(_id);
require(thisItem.category == 0, "can only enter wearables");
for(uint256 i = 0; i < s.raffles.length; i++){
if(thisItem.rarityScoreModifier == s.raffles[i].brsMultiplier){
require(s.raffles[i].raffleActive, "raffle not active");
require(s.raffles[i].entrantsMapping[msg.sender] == 0,"already entered in this raffle");
s.raffles[i].entrants.push(msg.sender);
s.raffles[i].entrantsMapping[msg.sender] = _id;
}
}
IERC1155(_tokenAddress).safeTransferFrom(msg.sender,address(this),_id,1,"");
}
function itemBalances(address _account) external view returns (ItemIdIO[] memory bals_) {
return s.aavegotchiDiamond.itemBalances(_account);
}
function isApproved(address _account) public view returns (bool){
IERC1155(im_diamondAddress).isApprovedForAll(_account,address(this));
}
function getEntrants(uint256 _raffleId) public view returns(address[] memory _entrants){
_entrants = s.raffles[_raffleId].entrants;
}
function isWinner(address _address) public view returns(bool){
for(uint256 i = 0; i < 6; i++){
if(getWinner(i) == _address){return true;}
}
}
function getWinningIndex(uint256 _raffleId) public view returns(uint256){
Raffle storage raffle = s.raffles[_raffleId];
uint256 randomNumber = raffle.randomNumber;
//if(randomNumber == 0){return address(0);}
return uint256(
keccak256(abi.encodePacked(randomNumber, _raffleId))
) % raffle.entrants.length;
}
function getAuctionState(uint256 _raffleId) public view returns(uint256){
Raffle storage raffle = s.raffles[_raffleId];
if(raffle.raffleActive == true){
return 0;
}
else if(raffle.randomNumberPending == true){
return 1;
}
else{
return 2;
}
}
function getWinner(uint256 _raffleId) public view returns(address _winner){
require(_raffleId < s.raffles.length, "Raffle: Raffle does not exist");
Raffle storage raffle = s.raffles[_raffleId];
//require(raffle.raffleActive == false, "raffle still active");
if(raffle.raffleActive == true){
return address(0);
}
require(raffle.randomNumberPending == false, "waiting on VRF");
uint256 winningIndex = getWinningIndex(_raffleId);
return s.raffles[_raffleId].entrants[winningIndex];
}
function claimAllPrizes(address _entrant) public{
//make sure this entrant has winnings
require(isWinner(_entrant),"Sorry, no prizes for you");
//go through each raffle and collect any winnings
for(uint256 i = 0; i < 6; i++){
Raffle storage raffle = s.raffles[i];
uint256 randomNumber = raffle.randomNumber;
//winner has to have been drawn, function must be called by winner or contract owner, and entrant must be winner
if(
randomNumber > 0 &&
(msg.sender == _entrant || msg.sender == s.contractOwner) &&
getWinner(i) == _entrant
){
//cycle through each entry and send wearable to the winner
for(uint256 j = 0; j<raffle.entrants.length; j++){
uint256 entrantItem = raffle.entrantsMapping[raffle.entrants[j]];
IERC1155(im_diamondAddress).safeTransferFrom(address(this),_entrant,entrantItem,1,"");
}
resetRaffle(i);
if(msg.sender == _entrant){
ghst.transferFrom(msg.sender, address(this), 10000000000000000000);
}
}
}
}
/**
* @notice Claim prizes won
* @dev All items in _wins are verified as actually won by the address that calls this function and reverts otherwise.
* @dev Each entrant address can only claim prizes once, so be sure to include all entries and prizes won.
* @dev Prizes are transfered to the address that calls this function.
* @dev Due to the possibility that an entrant does not claim all the prizes he/she won or the gas cost is too high,
* the contractOwner can claim prizes for an entrant. This needs to be used with care so that contractOwner does not
* accidentally claim prizes for an entrant that have already been claimed for or by the entrant.
* @param _entrant The entrant that won the prizes
* @param _raffleId The raffle that prizes were won in.
*
*/
function claimPrize(
uint256 _raffleId,
address _entrant
) public {
require(_raffleId < s.raffles.length, "Raffle: Raffle does not exist");
Raffle storage raffle = s.raffles[_raffleId];
uint256 randomNumber = raffle.randomNumber;
require(randomNumber > 0, "Raffle: Random number not generated yet");
// contractOwner can claim prizes for the entrant. Prizes are only transferred to the entrant
require(msg.sender == _entrant || msg.sender == s.contractOwner, "Raffle: Not claimed by owner or contractOwner");
require(getWinner(_raffleId) == _entrant, "not a winner");
//cycle through each entry and send wearable to the winner
for(uint256 i = 0; i<raffle.entrants.length; i++){
uint256 entrantItem = raffle.entrantsMapping[raffle.entrants[i]];
IERC1155(im_diamondAddress).safeTransferFrom(address(this),_entrant,entrantItem,1,"");
}
resetRaffle(_raffleId);
}
}
|
get the item type the entrant enteredsend back the wearable the entrant enterednow we need to remove this entrant's info from this raffleif the entrant was the last entrant, we can just delete him from the arrayotherwise, deleting him will leave a gap, so we copy in the last entrant to his spot
|
function withdrawEntry(uint256 _raffleId) public{
IERC1155 wearables = IERC1155(im_diamondAddress);
uint256 itemId = s.raffles[_raffleId].entrantsMapping[msg.sender];
wearables.safeTransferFrom(address(this), msg.sender, itemId, 1, "0x");
s.raffles[_raffleId].entrantsMapping[msg.sender] = 0;
for(uint i = 0; i < s.raffles[_raffleId].entrants.length; i++){
if(s.raffles[_raffleId].entrants[i] == msg.sender){
else{
delete s.raffles[_raffleId].entrants[i];
s.raffles[_raffleId].entrants[i] = s.raffles[_raffleId].entrants[s.raffles[_raffleId].entrants.length-1];
delete s.raffles[_raffleId].entrants[s.raffles[_raffleId].entrants.length-1];
}
}
}
}
require(raffleId < s.raffles.length, "Raffle: Raffle does not exist");
Raffle storage raffle = s.raffles[raffleId];
require(raffle.randomNumber == 0, "Raffle: Random number already generated");
s.raffles[raffleId].randomNumber = uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp)));
console.log("Random number is: ", s.raffles[raffleId].randomNumber);
address winner = getWinner(_raffleId);
console.log("Winner should be: ",winner);
raffle.randomNumberPending = false;
| 14,094,515 |
./full_match/100/0x048DC80e3A072914dA7c8bB77C97309a69E3B206/sources/contracts/FreeBetV2.sol
|
Withdraw bet payout for bettor (reward or 0) azuroBetId The ID of Azuro bet to withdraw/
|
function withdrawPayout(uint256 azuroBetId) external {
uint128 payout = _withdrawPayout(azuroBetId);
if (payout > 0) {
TransferHelper.safeTransfer(token, msg.sender, payout);
}
}
| 14,270,841 |
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "../core/DaoConstants.sol";
import "../core/DaoRegistry.sol";
import "../guards/MemberGuard.sol";
import "../guards/AdapterGuard.sol";
import "./interfaces/IConfiguration.sol";
import "../adapters/interfaces/IVoting.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
contract ConfigurationContract is
IConfiguration,
DaoConstants,
MemberGuard,
AdapterGuard
{
mapping(address => mapping(bytes32 => Configuration[]))
private _configurations;
/*
* default fallback function to prevent from sending ether to the contract
*/
receive() external payable {
revert("fallback revert");
}
function submitProposal(
DaoRegistry dao,
bytes32 proposalId,
Configuration[] calldata configs,
bytes calldata data
) external override onlyMember(dao) reentrancyGuard(dao) {
require(configs.length > 0, "missing configs");
dao.submitProposal(proposalId);
Configuration[] storage newConfigs = _configurations[address(dao)][
proposalId
];
for (uint256 i = 0; i < configs.length; i++) {
Configuration memory config = configs[i];
newConfigs.push(
Configuration({
key: config.key,
configType: config.configType,
numericValue: config.numericValue,
addressValue: config.addressValue
})
);
}
IVoting votingContract = IVoting(dao.getAdapterAddress(VOTING));
address sponsoredBy = votingContract.getSenderAddress(
dao,
address(this),
data,
msg.sender
);
dao.sponsorProposal(proposalId, sponsoredBy, address(votingContract));
votingContract.startNewVotingForProposal(dao, proposalId, data);
}
function processProposal(DaoRegistry dao, bytes32 proposalId)
external
override
reentrancyGuard(dao)
{
dao.processProposal(proposalId);
IVoting votingContract = IVoting(dao.votingAdapter(proposalId));
require(address(votingContract) != address(0), "adapter not found");
require(
votingContract.voteResult(dao, proposalId) ==
IVoting.VotingState.PASS,
"proposal did not pass"
);
Configuration[] memory configs = _configurations[address(dao)][
proposalId
];
for (uint256 i = 0; i < configs.length; i++) {
Configuration memory config = configs[i];
if (ConfigType.NUMERIC == config.configType) {
dao.setConfiguration(config.key, config.numericValue);
} else if (ConfigType.ADDRESS == config.configType) {
dao.setAddressConfiguration(config.key, config.addressValue);
}
}
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "../../core/DaoRegistry.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
interface IConfiguration {
enum ConfigType {
NUMERIC,
ADDRESS
}
struct Configuration {
bytes32 key;
uint256 numericValue;
address addressValue;
ConfigType configType;
}
function submitProposal(
DaoRegistry dao,
bytes32 proposalId,
Configuration[] calldata configs,
bytes calldata data
) external;
function processProposal(DaoRegistry dao, bytes32 proposalId) external;
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "../../core/DaoRegistry.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
interface IVoting {
enum VotingState {
NOT_STARTED,
TIE,
PASS,
NOT_PASS,
IN_PROGRESS,
GRACE_PERIOD
}
function getAdapterName() external pure returns (string memory);
function startNewVotingForProposal(
DaoRegistry dao,
bytes32 proposalId,
bytes calldata data
) external;
function getSenderAddress(
DaoRegistry dao,
address actionId,
bytes memory data,
address sender
) external returns (address);
function voteResult(DaoRegistry dao, bytes32 proposalId)
external
returns (VotingState state);
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
/**
MIT License
Copyright (c) 2020 Openlaw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
abstract contract DaoConstants {
// Adapters
bytes32 internal constant VOTING = keccak256("voting");
bytes32 internal constant ONBOARDING = keccak256("onboarding");
bytes32 internal constant NONVOTING_ONBOARDING =
keccak256("nonvoting-onboarding");
bytes32 internal constant TRIBUTE = keccak256("tribute");
bytes32 internal constant FINANCING = keccak256("financing");
bytes32 internal constant MANAGING = keccak256("managing");
bytes32 internal constant RAGEQUIT = keccak256("ragequit");
bytes32 internal constant GUILDKICK = keccak256("guildkick");
bytes32 internal constant EXECUTION = keccak256("execution");
bytes32 internal constant CONFIGURATION = keccak256("configuration");
bytes32 internal constant DISTRIBUTE = keccak256("distribute");
bytes32 internal constant TRIBUTE_NFT = keccak256("tribute-nft");
// Extensions
bytes32 internal constant BANK = keccak256("bank");
bytes32 internal constant NFT = keccak256("nft");
bytes32 internal constant ERC20_EXT = keccak256("erc20-ext");
bytes32 internal constant EXECUTOR_EXT = keccak256("executor-ext");
// Reserved Addresses
address internal constant GUILD = address(0xdead);
address internal constant TOTAL = address(0xbabe);
address internal constant ESCROW = address(0x4bec);
address internal constant UNITS = address(0xFF1CE);
address internal constant LOOT = address(0xB105F00D);
address internal constant ETH_TOKEN = address(0x0);
address internal constant MEMBER_COUNT = address(0xDECAFBAD);
uint8 internal constant MAX_TOKENS_GUILD_BANK = 200;
//helper
function getFlag(uint256 flags, uint256 flag) public pure returns (bool) {
return (flags >> uint8(flag)) % 2 == 1;
}
function setFlag(
uint256 flags,
uint256 flag,
bool value
) public pure returns (uint256) {
if (getFlag(flags, flag) != value) {
if (value) {
return flags + 2**flag;
} else {
return flags - 2**flag;
}
} else {
return flags;
}
}
/**
* @notice Checks if a given address is reserved.
*/
function isNotReservedAddress(address addr) public pure returns (bool) {
return addr != GUILD && addr != TOTAL && addr != ESCROW;
}
/**
* @notice Checks if a given address is zeroed.
*/
function isNotZeroAddress(address addr) public pure returns (bool) {
return addr != address(0x0);
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "./DaoConstants.sol";
import "../guards/AdapterGuard.sol";
import "../guards/MemberGuard.sol";
import "../extensions/IExtension.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
contract DaoRegistry is MemberGuard, AdapterGuard {
bool public initialized = false; // internally tracks deployment under eip-1167 proxy pattern
enum DaoState {
CREATION,
READY
}
/*
* EVENTS
*/
/// @dev - Events for Proposals
event SubmittedProposal(bytes32 proposalId, uint256 flags);
event SponsoredProposal(
bytes32 proposalId,
uint256 flags,
address votingAdapter
);
event ProcessedProposal(bytes32 proposalId, uint256 flags);
event AdapterAdded(
bytes32 adapterId,
address adapterAddress,
uint256 flags
);
event AdapterRemoved(bytes32 adapterId);
event ExtensionAdded(bytes32 extensionId, address extensionAddress);
event ExtensionRemoved(bytes32 extensionId);
/// @dev - Events for Members
event UpdateDelegateKey(address memberAddress, address newDelegateKey);
event ConfigurationUpdated(bytes32 key, uint256 value);
event AddressConfigurationUpdated(bytes32 key, address value);
enum MemberFlag {
EXISTS
}
enum ProposalFlag {
EXISTS,
SPONSORED,
PROCESSED
}
enum AclFlag {
REPLACE_ADAPTER,
SUBMIT_PROPOSAL,
UPDATE_DELEGATE_KEY,
SET_CONFIGURATION,
ADD_EXTENSION,
REMOVE_EXTENSION,
NEW_MEMBER
}
/*
* STRUCTURES
*/
struct Proposal {
// the structure to track all the proposals in the DAO
address adapterAddress; // the adapter address that called the functions to change the DAO state
uint256 flags; // flags to track the state of the proposal: exist, sponsored, processed, canceled, etc.
}
struct Member {
// the structure to track all the members in the DAO
uint256 flags; // flags to track the state of the member: exists, etc
}
struct Checkpoint {
// A checkpoint for marking number of votes from a given block
uint96 fromBlock;
uint160 amount;
}
struct DelegateCheckpoint {
// A checkpoint for marking number of votes from a given block
uint96 fromBlock;
address delegateKey;
}
struct AdapterEntry {
bytes32 id;
uint256 acl;
}
struct ExtensionEntry {
bytes32 id;
mapping(address => uint256) acl;
}
/*
* PUBLIC VARIABLES
*/
mapping(address => Member) public members; // the map to track all members of the DAO
address[] private _members;
// delegate key => member address mapping
mapping(address => address) public memberAddressesByDelegatedKey;
// memberAddress => checkpointNum => DelegateCheckpoint
mapping(address => mapping(uint32 => DelegateCheckpoint)) checkpoints;
// memberAddress => numDelegateCheckpoints
mapping(address => uint32) numCheckpoints;
DaoState public state;
/// @notice The map that keeps track of all proposasls submitted to the DAO
mapping(bytes32 => Proposal) public proposals;
/// @notice The map that tracks the voting adapter address per proposalId
mapping(bytes32 => address) public votingAdapter;
/// @notice The map that keeps track of all adapters registered in the DAO
mapping(bytes32 => address) public adapters;
/// @notice The inverse map to get the adapter id based on its address
mapping(address => AdapterEntry) public inverseAdapters;
/// @notice The map that keeps track of all extensions registered in the DAO
mapping(bytes32 => address) public extensions;
/// @notice The inverse map to get the extension id based on its address
mapping(address => ExtensionEntry) public inverseExtensions;
/// @notice The map that keeps track of configuration parameters for the DAO and adapters
mapping(bytes32 => uint256) public mainConfiguration;
mapping(bytes32 => address) public addressConfiguration;
uint256 public lockedAt;
/// @notice Clonable contract must have an empty constructor
// constructor() {
// }
/**
* @notice Initialises the DAO
* @dev Involves initialising available tokens, checkpoints, and membership of creator
* @dev Can only be called once
* @param creator The DAO's creator, who will be an initial member
* @param payer The account which paid for the transaction to create the DAO, who will be an initial member
*/
function initialize(address creator, address payer) external {
require(!initialized, "dao already initialized");
potentialNewMember(msg.sender);
potentialNewMember(payer);
potentialNewMember(creator);
initialized = true;
}
/**
* @notice default fallback function to prevent from sending ether to the contract
*/
receive() external payable {
revert("you cannot send money back directly");
}
/**
* @dev Sets the state of the dao to READY
*/
function finalizeDao() external {
state = DaoState.READY;
}
function lockSession() external {
if (isAdapter(msg.sender) || isExtension(msg.sender)) {
lockedAt = block.number;
}
}
function unlockSession() external {
if (isAdapter(msg.sender) || isExtension(msg.sender)) {
lockedAt = 0;
}
}
/**
* @notice Sets a configuration value
* @dev Changes the value of a key in the configuration mapping
* @param key The configuration key for which the value will be set
* @param value The value to set the key
*/
function setConfiguration(bytes32 key, uint256 value)
external
hasAccess(this, AclFlag.SET_CONFIGURATION)
{
mainConfiguration[key] = value;
emit ConfigurationUpdated(key, value);
}
function potentialNewMember(address memberAddress)
public
hasAccess(this, AclFlag.NEW_MEMBER)
{
require(memberAddress != address(0x0), "invalid member address");
Member storage member = members[memberAddress];
if (!getFlag(member.flags, uint8(MemberFlag.EXISTS))) {
require(
memberAddressesByDelegatedKey[memberAddress] == address(0x0),
"member address already taken as delegated key"
);
member.flags = setFlag(
member.flags,
uint8(MemberFlag.EXISTS),
true
);
memberAddressesByDelegatedKey[memberAddress] = memberAddress;
_members.push(memberAddress);
}
address bankAddress = extensions[BANK];
if (bankAddress != address(0x0)) {
BankExtension bank = BankExtension(bankAddress);
if (bank.balanceOf(memberAddress, MEMBER_COUNT) == 0) {
bank.addToBalance(memberAddress, MEMBER_COUNT, 1);
}
}
}
/**
* @notice Sets an configuration value
* @dev Changes the value of a key in the configuration mapping
* @param key The configuration key for which the value will be set
* @param value The value to set the key
*/
function setAddressConfiguration(bytes32 key, address value)
external
hasAccess(this, AclFlag.SET_CONFIGURATION)
{
addressConfiguration[key] = value;
emit AddressConfigurationUpdated(key, value);
}
/**
* @return The configuration value of a particular key
* @param key The key to look up in the configuration mapping
*/
function getConfiguration(bytes32 key) external view returns (uint256) {
return mainConfiguration[key];
}
/**
* @return The configuration value of a particular key
* @param key The key to look up in the configuration mapping
*/
function getAddressConfiguration(bytes32 key)
external
view
returns (address)
{
return addressConfiguration[key];
}
/**
* @notice Adds a new extension to the registry
* @param extensionId The unique identifier of the new extension
* @param extension The address of the extension
* @param creator The DAO's creator, who will be an initial member
*/
function addExtension(
bytes32 extensionId,
IExtension extension,
address creator
) external hasAccess(this, AclFlag.ADD_EXTENSION) {
require(extensionId != bytes32(0), "extension id must not be empty");
require(
extensions[extensionId] == address(0x0),
"extension Id already in use"
);
extensions[extensionId] = address(extension);
inverseExtensions[address(extension)].id = extensionId;
extension.initialize(this, creator);
emit ExtensionAdded(extensionId, address(extension));
}
function setAclToExtensionForAdapter(
address extensionAddress,
address adapterAddress,
uint256 acl
) external hasAccess(this, AclFlag.ADD_EXTENSION) {
require(isAdapter(adapterAddress), "not an adapter");
require(isExtension(extensionAddress), "not an extension");
inverseExtensions[extensionAddress].acl[adapterAddress] = acl;
}
/**
* @notice Replaces an adapter in the registry in a single step.
* @notice It handles addition and removal of adapters as special cases.
* @dev It removes the current adapter if the adapterId maps to an existing adapter address.
* @dev It adds an adapter if the adapterAddress parameter is not zeroed.
* @param adapterId The unique identifier of the adapter
* @param adapterAddress The address of the new adapter or zero if it is a removal operation
* @param acl The flags indicating the access control layer or permissions of the new adapter
* @param keys The keys indicating the adapter configuration names.
* @param values The values indicating the adapter configuration values.
*/
function replaceAdapter(
bytes32 adapterId,
address adapterAddress,
uint128 acl,
bytes32[] calldata keys,
uint256[] calldata values
) external hasAccess(this, AclFlag.REPLACE_ADAPTER) {
require(adapterId != bytes32(0), "adapterId must not be empty");
address currentAdapterAddr = adapters[adapterId];
if (currentAdapterAddr != address(0x0)) {
delete inverseAdapters[currentAdapterAddr];
delete adapters[adapterId];
emit AdapterRemoved(adapterId);
}
for (uint256 i = 0; i < keys.length; i++) {
bytes32 key = keys[i];
uint256 value = values[i];
mainConfiguration[key] = value;
emit ConfigurationUpdated(key, value);
}
if (adapterAddress != address(0x0)) {
require(
inverseAdapters[adapterAddress].id == bytes32(0),
"adapterAddress already in use"
);
adapters[adapterId] = adapterAddress;
inverseAdapters[adapterAddress].id = adapterId;
inverseAdapters[adapterAddress].acl = acl;
emit AdapterAdded(adapterId, adapterAddress, acl);
}
}
/**
* @notice Removes an adapter from the registry
* @param extensionId The unique identifier of the extension
*/
function removeExtension(bytes32 extensionId)
external
hasAccess(this, AclFlag.REMOVE_EXTENSION)
{
require(extensionId != bytes32(0), "extensionId must not be empty");
require(
extensions[extensionId] != address(0x0),
"extensionId not registered"
);
delete inverseExtensions[extensions[extensionId]];
delete extensions[extensionId];
emit ExtensionRemoved(extensionId);
}
/**
* @notice Looks up if there is an extension of a given address
* @return Whether or not the address is an extension
* @param extensionAddr The address to look up
*/
function isExtension(address extensionAddr) public view returns (bool) {
return inverseExtensions[extensionAddr].id != bytes32(0);
}
/**
* @notice Looks up if there is an adapter of a given address
* @return Whether or not the address is an adapter
* @param adapterAddress The address to look up
*/
function isAdapter(address adapterAddress) public view returns (bool) {
return inverseAdapters[adapterAddress].id != bytes32(0);
}
/**
* @notice Checks if an adapter has a given ACL flag
* @return Whether or not the given adapter has the given flag set
* @param adapterAddress The address to look up
* @param flag The ACL flag to check against the given address
*/
function hasAdapterAccess(address adapterAddress, AclFlag flag)
public
view
returns (bool)
{
return getFlag(inverseAdapters[adapterAddress].acl, uint8(flag));
}
/**
* @notice Checks if an adapter has a given ACL flag
* @return Whether or not the given adapter has the given flag set
* @param adapterAddress The address to look up
* @param flag The ACL flag to check against the given address
*/
function hasAdapterAccessToExtension(
address adapterAddress,
address extensionAddress,
uint8 flag
) public view returns (bool) {
return
isAdapter(adapterAddress) &&
getFlag(
inverseExtensions[extensionAddress].acl[adapterAddress],
uint8(flag)
);
}
/**
* @return The address of a given adapter ID
* @param adapterId The ID to look up
*/
function getAdapterAddress(bytes32 adapterId)
external
view
returns (address)
{
require(adapters[adapterId] != address(0), "adapter not found");
return adapters[adapterId];
}
/**
* @return The address of a given extension Id
* @param extensionId The ID to look up
*/
function getExtensionAddress(bytes32 extensionId)
external
view
returns (address)
{
require(extensions[extensionId] != address(0), "extension not found");
return extensions[extensionId];
}
/**
* PROPOSALS
*/
/**
* @notice Submit proposals to the DAO registry
*/
function submitProposal(bytes32 proposalId)
public
hasAccess(this, AclFlag.SUBMIT_PROPOSAL)
{
require(proposalId != bytes32(0), "invalid proposalId");
require(
!getProposalFlag(proposalId, ProposalFlag.EXISTS),
"proposalId must be unique"
);
proposals[proposalId] = Proposal(msg.sender, 1); // 1 means that only the first flag is being set i.e. EXISTS
emit SubmittedProposal(proposalId, 1);
}
/**
* @notice Sponsor proposals that were submitted to the DAO registry
* @dev adds SPONSORED to the proposal flag
* @param proposalId The ID of the proposal to sponsor
* @param sponsoringMember The member who is sponsoring the proposal
*/
function sponsorProposal(
bytes32 proposalId,
address sponsoringMember,
address votingAdapterAddr
) external onlyMember2(this, sponsoringMember) {
// also checks if the flag was already set
Proposal storage proposal = _setProposalFlag(
proposalId,
ProposalFlag.SPONSORED
);
uint256 flags = proposal.flags;
require(
proposal.adapterAddress == msg.sender,
"only the adapter that submitted the proposal can process it"
);
require(
!getFlag(flags, uint8(ProposalFlag.PROCESSED)),
"proposal already processed"
);
votingAdapter[proposalId] = votingAdapterAddr;
emit SponsoredProposal(proposalId, flags, votingAdapterAddr);
}
/**
* @notice Mark a proposal as processed in the DAO registry
* @param proposalId The ID of the proposal that is being processed
*/
function processProposal(bytes32 proposalId) external {
Proposal storage proposal = _setProposalFlag(
proposalId,
ProposalFlag.PROCESSED
);
require(proposal.adapterAddress == msg.sender, "err::adapter mismatch");
uint256 flags = proposal.flags;
emit ProcessedProposal(proposalId, flags);
}
/**
* @notice Sets a flag of a proposal
* @dev Reverts if the proposal is already processed
* @param proposalId The ID of the proposal to be changed
* @param flag The flag that will be set on the proposal
*/
function _setProposalFlag(bytes32 proposalId, ProposalFlag flag)
internal
returns (Proposal storage)
{
Proposal storage proposal = proposals[proposalId];
uint256 flags = proposal.flags;
require(
getFlag(flags, uint8(ProposalFlag.EXISTS)),
"proposal does not exist for this dao"
);
require(
proposal.adapterAddress == msg.sender,
"only the adapter that submitted the proposal can set its flag"
);
require(!getFlag(flags, uint8(flag)), "flag already set");
flags = setFlag(flags, uint8(flag), true);
proposals[proposalId].flags = flags;
return proposals[proposalId];
}
/*
* MEMBERS
*/
/**
* @return Whether or not a given address is a member of the DAO.
* @dev it will resolve by delegate key, not member address.
* @param addr The address to look up
*/
function isMember(address addr) public view returns (bool) {
address memberAddress = memberAddressesByDelegatedKey[addr];
return getMemberFlag(memberAddress, MemberFlag.EXISTS);
}
/**
* @return Whether or not a flag is set for a given proposal
* @param proposalId The proposal to check against flag
* @param flag The flag to check in the proposal
*/
function getProposalFlag(bytes32 proposalId, ProposalFlag flag)
public
view
returns (bool)
{
return getFlag(proposals[proposalId].flags, uint8(flag));
}
/**
* @return Whether or not a flag is set for a given member
* @param memberAddress The member to check against flag
* @param flag The flag to check in the member
*/
function getMemberFlag(address memberAddress, MemberFlag flag)
public
view
returns (bool)
{
return getFlag(members[memberAddress].flags, uint8(flag));
}
function getNbMembers() public view returns (uint256) {
return _members.length;
}
function getMemberAddress(uint256 index) public view returns (address) {
return _members[index];
}
/**
* @notice Updates the delegate key of a member
* @param memberAddr The member doing the delegation
* @param newDelegateKey The member who is being delegated to
*/
function updateDelegateKey(address memberAddr, address newDelegateKey)
external
hasAccess(this, AclFlag.UPDATE_DELEGATE_KEY)
{
require(newDelegateKey != address(0x0), "newDelegateKey cannot be 0");
// skip checks if member is setting the delegate key to their member address
if (newDelegateKey != memberAddr) {
require(
// newDelegate must not be delegated to
memberAddressesByDelegatedKey[newDelegateKey] == address(0x0),
"cannot overwrite existing delegated keys"
);
} else {
require(
memberAddressesByDelegatedKey[memberAddr] == address(0x0),
"address already taken as delegated key"
);
}
Member storage member = members[memberAddr];
require(
getFlag(member.flags, uint8(MemberFlag.EXISTS)),
"member does not exist"
);
// Reset the delegation of the previous delegate
memberAddressesByDelegatedKey[
getCurrentDelegateKey(memberAddr)
] = address(0x0);
memberAddressesByDelegatedKey[newDelegateKey] = memberAddr;
_createNewDelegateCheckpoint(memberAddr, newDelegateKey);
emit UpdateDelegateKey(memberAddr, newDelegateKey);
}
/**
* Public read-only functions
*/
/**
* @param checkAddr The address to check for a delegate
* @return the delegated address or the checked address if it is not a delegate
*/
function getAddressIfDelegated(address checkAddr)
public
view
returns (address)
{
address delegatedKey = memberAddressesByDelegatedKey[checkAddr];
return delegatedKey == address(0x0) ? checkAddr : delegatedKey;
}
/**
* @param memberAddr The member whose delegate will be returned
* @return the delegate key at the current time for a member
*/
function getCurrentDelegateKey(address memberAddr)
public
view
returns (address)
{
uint32 nCheckpoints = numCheckpoints[memberAddr];
return
nCheckpoints > 0
? checkpoints[memberAddr][nCheckpoints - 1].delegateKey
: memberAddr;
}
/**
* @param memberAddr The member address to look up
* @return The delegate key address for memberAddr at the second last checkpoint number
*/
function getPreviousDelegateKey(address memberAddr)
public
view
returns (address)
{
uint32 nCheckpoints = numCheckpoints[memberAddr];
return
nCheckpoints > 1
? checkpoints[memberAddr][nCheckpoints - 2].delegateKey
: memberAddr;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param memberAddr The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorDelegateKey(address memberAddr, uint256 blockNumber)
external
view
returns (address)
{
require(
blockNumber < block.number,
"Uni::getPriorDelegateKey: not yet determined"
);
uint32 nCheckpoints = numCheckpoints[memberAddr];
if (nCheckpoints == 0) {
return memberAddr;
}
// First check most recent balance
if (
checkpoints[memberAddr][nCheckpoints - 1].fromBlock <= blockNumber
) {
return checkpoints[memberAddr][nCheckpoints - 1].delegateKey;
}
// Next check implicit zero balance
if (checkpoints[memberAddr][0].fromBlock > blockNumber) {
return memberAddr;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
DelegateCheckpoint memory cp = checkpoints[memberAddr][center];
if (cp.fromBlock == blockNumber) {
return cp.delegateKey;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[memberAddr][lower].delegateKey;
}
/**
* @notice Creates a new delegate checkpoint of a certain member
* @param member The member whose delegate checkpoints will be added to
* @param newDelegateKey The delegate key that will be written into the new checkpoint
*/
function _createNewDelegateCheckpoint(
address member,
address newDelegateKey
) internal {
uint32 nCheckpoints = numCheckpoints[member];
if (
nCheckpoints > 0 &&
checkpoints[member][nCheckpoints - 1].fromBlock == block.number
) {
checkpoints[member][nCheckpoints - 1].delegateKey = newDelegateKey;
} else {
checkpoints[member][nCheckpoints] = DelegateCheckpoint(
uint96(block.number),
newDelegateKey
);
numCheckpoints[member] = nCheckpoints + 1;
}
}
}
pragma solidity ^0.8.0;
import "../core/DaoRegistry.sol";
// SPDX-License-Identifier: MIT
/**
MIT License
Copyright (c) 2020 Openlaw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
interface IExtension {
function initialize(DaoRegistry dao, address creator) external;
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "../../core/DaoConstants.sol";
import "../../core/DaoRegistry.sol";
import "../IExtension.sol";
import "../../guards/AdapterGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
contract BankExtension is DaoConstants, AdapterGuard, IExtension {
using Address for address payable;
using SafeERC20 for IERC20;
uint8 public maxExternalTokens; // the maximum number of external tokens that can be stored in the bank
bool public initialized = false; // internally tracks deployment under eip-1167 proxy pattern
DaoRegistry public dao;
enum AclFlag {
ADD_TO_BALANCE,
SUB_FROM_BALANCE,
INTERNAL_TRANSFER,
WITHDRAW,
EXECUTE,
REGISTER_NEW_TOKEN,
REGISTER_NEW_INTERNAL_TOKEN,
UPDATE_TOKEN
}
modifier noProposal() {
require(dao.lockedAt() < block.number, "proposal lock");
_;
}
/// @dev - Events for Bank
event NewBalance(address member, address tokenAddr, uint160 amount);
event Withdraw(address account, address tokenAddr, uint160 amount);
/*
* STRUCTURES
*/
struct Checkpoint {
// A checkpoint for marking number of votes from a given block
uint96 fromBlock;
uint160 amount;
}
address[] public tokens;
address[] public internalTokens;
// tokenAddress => availability
mapping(address => bool) public availableTokens;
mapping(address => bool) public availableInternalTokens;
// tokenAddress => memberAddress => checkpointNum => Checkpoint
mapping(address => mapping(address => mapping(uint32 => Checkpoint)))
public checkpoints;
// tokenAddress => memberAddress => numCheckpoints
mapping(address => mapping(address => uint32)) public numCheckpoints;
/// @notice Clonable contract must have an empty constructor
// constructor() {
// }
modifier hasExtensionAccess(AclFlag flag) {
require(
address(this) == msg.sender ||
address(dao) == msg.sender ||
dao.state() == DaoRegistry.DaoState.CREATION ||
dao.hasAdapterAccessToExtension(
msg.sender,
address(this),
uint8(flag)
),
"bank::accessDenied"
);
_;
}
/**
* @notice Initialises the DAO
* @dev Involves initialising available tokens, checkpoints, and membership of creator
* @dev Can only be called once
* @param creator The DAO's creator, who will be an initial member
*/
function initialize(DaoRegistry _dao, address creator) external override {
require(!initialized, "bank already initialized");
require(_dao.isMember(creator), "bank::not member");
dao = _dao;
initialized = true;
availableInternalTokens[UNITS] = true;
internalTokens.push(UNITS);
availableInternalTokens[MEMBER_COUNT] = true;
internalTokens.push(MEMBER_COUNT);
uint256 nbMembers = _dao.getNbMembers();
for (uint256 i = 0; i < nbMembers; i++) {
addToBalance(_dao.getMemberAddress(i), MEMBER_COUNT, 1);
}
_createNewAmountCheckpoint(creator, UNITS, 1);
_createNewAmountCheckpoint(TOTAL, UNITS, 1);
}
function withdraw(
address payable member,
address tokenAddr,
uint256 amount
) external hasExtensionAccess(AclFlag.WITHDRAW) {
require(
balanceOf(member, tokenAddr) >= amount,
"bank::withdraw::not enough funds"
);
subtractFromBalance(member, tokenAddr, amount);
if (tokenAddr == ETH_TOKEN) {
member.sendValue(amount);
} else {
IERC20 erc20 = IERC20(tokenAddr);
erc20.safeTransfer(member, amount);
}
emit Withdraw(member, tokenAddr, uint160(amount));
}
/**
* @return Whether or not the given token is an available internal token in the bank
* @param token The address of the token to look up
*/
function isInternalToken(address token) external view returns (bool) {
return availableInternalTokens[token];
}
/**
* @return Whether or not the given token is an available token in the bank
* @param token The address of the token to look up
*/
function isTokenAllowed(address token) public view returns (bool) {
return availableTokens[token];
}
/**
* @notice Sets the maximum amount of external tokens allowed in the bank
* @param maxTokens The maximum amount of token allowed
*/
function setMaxExternalTokens(uint8 maxTokens) external {
require(!initialized, "bank already initialized");
require(
maxTokens > 0 && maxTokens <= MAX_TOKENS_GUILD_BANK,
"max number of external tokens should be (0,200)"
);
maxExternalTokens = maxTokens;
}
/*
* BANK
*/
/**
* @notice Registers a potential new token in the bank
* @dev Can not be a reserved token or an available internal token
* @param token The address of the token
*/
function registerPotentialNewToken(address token)
external
hasExtensionAccess(AclFlag.REGISTER_NEW_TOKEN)
{
require(isNotReservedAddress(token), "reservedToken");
require(!availableInternalTokens[token], "internalToken");
require(
tokens.length <= maxExternalTokens,
"exceeds the maximum tokens allowed"
);
if (!availableTokens[token]) {
availableTokens[token] = true;
tokens.push(token);
}
}
/**
* @notice Registers a potential new internal token in the bank
* @dev Can not be a reserved token or an available token
* @param token The address of the token
*/
function registerPotentialNewInternalToken(address token)
external
hasExtensionAccess(AclFlag.REGISTER_NEW_INTERNAL_TOKEN)
{
require(isNotReservedAddress(token), "reservedToken");
require(!availableTokens[token], "availableToken");
if (!availableInternalTokens[token]) {
availableInternalTokens[token] = true;
internalTokens.push(token);
}
}
function updateToken(address tokenAddr)
external
hasExtensionAccess(AclFlag.UPDATE_TOKEN)
{
require(isTokenAllowed(tokenAddr), "token not allowed");
uint256 totalBalance = balanceOf(TOTAL, tokenAddr);
uint256 realBalance;
if (tokenAddr == ETH_TOKEN) {
realBalance = address(this).balance;
} else {
IERC20 erc20 = IERC20(tokenAddr);
realBalance = erc20.balanceOf(address(this));
}
if (totalBalance < realBalance) {
addToBalance(GUILD, tokenAddr, realBalance - totalBalance);
} else if (totalBalance > realBalance) {
uint256 tokensToRemove = totalBalance - realBalance;
uint256 guildBalance = balanceOf(GUILD, tokenAddr);
if (guildBalance > tokensToRemove) {
subtractFromBalance(GUILD, tokenAddr, tokensToRemove);
} else {
subtractFromBalance(GUILD, tokenAddr, guildBalance);
}
}
}
/**
* Public read-only functions
*/
/**
* Internal bookkeeping
*/
/**
* @return The token from the bank of a given index
* @param index The index to look up in the bank's tokens
*/
function getToken(uint256 index) external view returns (address) {
return tokens[index];
}
/**
* @return The amount of token addresses in the bank
*/
function nbTokens() external view returns (uint256) {
return tokens.length;
}
/**
* @return All the tokens registered in the bank.
*/
function getTokens() external view returns (address[] memory) {
return tokens;
}
/**
* @return The internal token at a given index
* @param index The index to look up in the bank's array of internal tokens
*/
function getInternalToken(uint256 index) external view returns (address) {
return internalTokens[index];
}
/**
* @return The amount of internal token addresses in the bank
*/
function nbInternalTokens() external view returns (uint256) {
return internalTokens.length;
}
/**
* @notice Adds to a member's balance of a given token
* @param member The member whose balance will be updated
* @param token The token to update
* @param amount The new balance
*/
function addToBalance(
address member,
address token,
uint256 amount
) public payable hasExtensionAccess(AclFlag.ADD_TO_BALANCE) {
require(
availableTokens[token] || availableInternalTokens[token],
"unknown token address"
);
uint256 newAmount = balanceOf(member, token) + amount;
uint256 newTotalAmount = balanceOf(TOTAL, token) + amount;
_createNewAmountCheckpoint(member, token, newAmount);
_createNewAmountCheckpoint(TOTAL, token, newTotalAmount);
}
/**
* @notice Remove from a member's balance of a given token
* @param member The member whose balance will be updated
* @param token The token to update
* @param amount The new balance
*/
function subtractFromBalance(
address member,
address token,
uint256 amount
) public hasExtensionAccess(AclFlag.SUB_FROM_BALANCE) {
uint256 newAmount = balanceOf(member, token) - amount;
uint256 newTotalAmount = balanceOf(TOTAL, token) - amount;
_createNewAmountCheckpoint(member, token, newAmount);
_createNewAmountCheckpoint(TOTAL, token, newTotalAmount);
}
/**
* @notice Make an internal token transfer
* @param from The member who is sending tokens
* @param to The member who is receiving tokens
* @param amount The new amount to transfer
*/
function internalTransfer(
address from,
address to,
address token,
uint256 amount
) public hasExtensionAccess(AclFlag.INTERNAL_TRANSFER) {
uint256 newAmount = balanceOf(from, token) - amount;
uint256 newAmount2 = balanceOf(to, token) + amount;
_createNewAmountCheckpoint(from, token, newAmount);
_createNewAmountCheckpoint(to, token, newAmount2);
}
/**
* @notice Returns an member's balance of a given token
* @param member The address to look up
* @param tokenAddr The token where the member's balance of which will be returned
* @return The amount in account's tokenAddr balance
*/
function balanceOf(address member, address tokenAddr)
public
view
returns (uint160)
{
uint32 nCheckpoints = numCheckpoints[tokenAddr][member];
return
nCheckpoints > 0
? checkpoints[tokenAddr][member][nCheckpoints - 1].amount
: 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorAmount(
address account,
address tokenAddr,
uint256 blockNumber
) external view returns (uint256) {
require(
blockNumber < block.number,
"Uni::getPriorAmount: not yet determined"
);
uint32 nCheckpoints = numCheckpoints[tokenAddr][account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (
checkpoints[tokenAddr][account][nCheckpoints - 1].fromBlock <=
blockNumber
) {
return checkpoints[tokenAddr][account][nCheckpoints - 1].amount;
}
// Next check implicit zero balance
if (checkpoints[tokenAddr][account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[tokenAddr][account][center];
if (cp.fromBlock == blockNumber) {
return cp.amount;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[tokenAddr][account][lower].amount;
}
/**
* @notice Creates a new amount checkpoint for a token of a certain member
* @dev Reverts if the amount is greater than 2**64-1
* @param member The member whose checkpoints will be added to
* @param token The token of which the balance will be changed
* @param amount The amount to be written into the new checkpoint
*/
function _createNewAmountCheckpoint(
address member,
address token,
uint256 amount
) internal {
bool isValidToken = false;
if (availableInternalTokens[token]) {
require(
amount < type(uint88).max,
"token amount exceeds the maximum limit for internal tokens"
);
isValidToken = true;
} else if (availableTokens[token]) {
require(
amount < type(uint160).max,
"token amount exceeds the maximum limit for external tokens"
);
isValidToken = true;
}
uint160 newAmount = uint160(amount);
require(isValidToken, "token not registered");
uint32 nCheckpoints = numCheckpoints[token][member];
if (
nCheckpoints > 0 &&
checkpoints[token][member][nCheckpoints - 1].fromBlock ==
block.number
) {
checkpoints[token][member][nCheckpoints - 1].amount = newAmount;
} else {
checkpoints[token][member][nCheckpoints] = Checkpoint(
uint96(block.number),
newAmount
);
numCheckpoints[token][member] = nCheckpoints + 1;
}
emit NewBalance(member, token, newAmount);
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "../core/DaoRegistry.sol";
import "../extensions/IExtension.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
abstract contract AdapterGuard {
/**
* @dev Only registered adapters are allowed to execute the function call.
*/
modifier onlyAdapter(DaoRegistry dao) {
require(
(dao.state() == DaoRegistry.DaoState.CREATION &&
creationModeCheck(dao)) || dao.isAdapter(msg.sender),
"onlyAdapter"
);
_;
}
modifier reentrancyGuard(DaoRegistry dao) {
require(dao.lockedAt() != block.number, "reentrancy guard");
dao.lockSession();
_;
dao.unlockSession();
}
modifier executorFunc(DaoRegistry dao) {
address executorAddr = dao.getExtensionAddress(
keccak256("executor-ext")
);
require(address(this) == executorAddr, "only callable by the executor");
_;
}
modifier hasAccess(DaoRegistry dao, DaoRegistry.AclFlag flag) {
require(
(dao.state() == DaoRegistry.DaoState.CREATION &&
creationModeCheck(dao)) ||
dao.hasAdapterAccess(msg.sender, flag),
"accessDenied"
);
_;
}
function creationModeCheck(DaoRegistry dao) internal view returns (bool) {
return
dao.getNbMembers() == 0 ||
dao.isMember(msg.sender) ||
dao.isAdapter(msg.sender);
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "../core/DaoRegistry.sol";
import "../extensions/bank/Bank.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
abstract contract MemberGuard is DaoConstants {
/**
* @dev Only members of the DAO are allowed to execute the function call.
*/
modifier onlyMember(DaoRegistry dao) {
_onlyMember(dao, msg.sender);
_;
}
modifier onlyMember2(DaoRegistry dao, address _addr) {
_onlyMember(dao, _addr);
_;
}
function _onlyMember(DaoRegistry dao, address _addr) internal view {
require(isActiveMember(dao, _addr), "onlyMember");
}
function isActiveMember(DaoRegistry dao, address _addr)
public
view
returns (bool)
{
address bankAddress = dao.extensions(BANK);
if (bankAddress != address(0x0)) {
address memberAddr = dao.getAddressIfDelegated(_addr);
return BankExtension(bankAddress).balanceOf(memberAddr, UNITS) > 0;
}
return dao.isMember(_addr);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
Initialises the DAO Involves initialising available tokens, checkpoints, and membership of creator Can only be called once creator The DAO's creator, who will be an initial member/
|
function initialize(DaoRegistry _dao, address creator) external override {
require(!initialized, "bank already initialized");
require(_dao.isMember(creator), "bank::not member");
dao = _dao;
initialized = true;
availableInternalTokens[UNITS] = true;
internalTokens.push(UNITS);
availableInternalTokens[MEMBER_COUNT] = true;
internalTokens.push(MEMBER_COUNT);
uint256 nbMembers = _dao.getNbMembers();
for (uint256 i = 0; i < nbMembers; i++) {
addToBalance(_dao.getMemberAddress(i), MEMBER_COUNT, 1);
}
_createNewAmountCheckpoint(creator, UNITS, 1);
_createNewAmountCheckpoint(TOTAL, UNITS, 1);
}
| 317,245 |
./partial_match/1/0xf52459E8BC708d55400c167E0d77ED49641226D3/sources/OErc20Delegator.sol
|
A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock) token The address of the ERC-20 token to sweep/
|
function sweepToken(EIP20NonStandardInterface token) external {
delegateToImplementation(abi.encodeWithSignature("sweepToken(address)", token));
}
| 2,741,140 |
// SPDX-License-Identifier: MIT
pragma solidity >= 0.8.4;
import "./IERC721Receiver.sol";
import "./IERC721Metadata.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol';
contract SparkLink is Ownable, ERC165, IERC721, IERC721Metadata{
using Address for address;
using Counters for Counters.Counter;
using SafeERC20 for IERC20;
Counters.Counter private _issueIds;
/*
Abstract struct Issue {
uint32 total_amount;
bool is_free
bool is_ND;
bool is_NC;
uint16 shill_times;
uint8 royalty_fee;
}
This structure records some common attributes of a series of NFTs:
- `royalty_fee`: the proportion of royaltyes
- `shill_times`: the number of times a single NFT can been shared
- `total_amount`: the total number of NFTs in the series
To reduce gas cost, this structure is actually stored in the `father_id` attibute of root NFT
- 0~31 `total_amount`
- 37 `is_free`
- 38 `is_NC`
- 39 `is_ND`
- 40~55 `shill_times`
- 56~63 `royalty_fee`
*/
struct Edition {
// This structure stores NFT related information:
// - `father_id`: For root NFT it stores issue abstract sturcture
// For other NFTs its stores the NFT Id of which NFT it `acceptShill` from
// - `shill_price`: The price should be paid when others `accpetShill` from this NFT
// - remaining_shill_times: The initial value is the shilltimes of the issue it belongs to
// When others `acceptShill` from this NFT, it will subtract one until its value is 0
// - `owner`: record the owner of this NFT
// - `ipfs_hash`: IPFS hash value of the URI where this NTF's metadata stores
// - `transfer_price`: The initial value is zero
// Set by `determinePrice` or `determinePriceAndApprove` before `transferFrom`
// It will be checked wether equal to msg.value when `transferFrom` is called
// After `transferFrom` this value will be set to zero
// - `profit`: record the profit owner can claim (include royalty fee it should conduct to its father NFT)
uint64 father_id;
uint128 shill_price;
uint16 remaining_shill_times;
address owner;
bytes32 ipfs_hash;
uint128 transfer_price;
uint128 profit;
}
// Emit when `determinePrice` success
event DeterminePrice(
uint64 indexed NFT_id,
uint128 transfer_price
);
// Emit when `determinePriceAndApprove` success
event DeterminePriceAndApprove(
uint64 indexed NFT_id,
uint128 transfer_price,
address indexed to
);
// Emit when `publish` success
// - `rootNFTId`: Record the Id of root NFT given to publisher
event Publish(
address indexed publisher,
uint64 indexed rootNFTId,
address token_addr
);
// Emit when claimProfit success
//- `amount`: Record the actual amount owner of this NFT received (profit - profit*royalty_fee/100)
event Claim(
uint64 indexed NFT_id,
address indexed receiver,
uint128 amount
);
// Emit when setURI success
event SetURI(
uint64 indexed NFT_id,
bytes32 old_URI,
bytes32 new_URI
);
event Label(
uint64 indexed NFT_id,
string content
);
event SetDAOFee(
uint8 old_DAO_fee,
uint8 new_DAO_fee
);
event SetLoosRatio(
uint8 old_loss_ratio,
uint8 new_loss_ratio
);
event SetDAORouter01(
address old_router_address,
address new_router_address
);
event SetDAORouter02(
address old_router_address,
address new_router_address
);
//----------------------------------------------------------------------------------------------------
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(address DAO_router_address01,address DAO_router_address02, address uniswapRouterAddress, address factoryAddress) {
uniswapV2Router = IUniswapV2Router02(uniswapRouterAddress);
uniswapV2Factory = IUniswapV2Factory(factoryAddress);
DAO_router01 = DAO_router_address01;
DAO_router02 = DAO_router_address02;
_name = "SparkLink";
_symbol = "SPL";
}
/**
* @dev Create a issue and mint a root NFT for buyer acceptShill from
*
* Requirements:
*
* - `_first_sell_price`: The price should be paid when others `accpetShill` from this NFT
* - `_royalty_fee`: The proportion of royaltyes, it represents the ratio of the father NFT's profit from the child NFT
* Its value should <= 100
* - `_shill_times`: the number of times a single NFT can been shared
* Its value should <= 65536
* - `_ipfs_hash`: IPFS hash value of the URI where this NTF's metadata stores
*
* - `token_address`: list of tokens(address) can be accepted for payment.
* `A token address` can be ERC-20 token contract address or `address(0)`(ETH).
*
* - `_is_free`:
* - `_is_NC`:
*
* - `_is_ND`:
* Emits a {Publish} event.
* - Emitted {Publish} event contains root NFT id.
*/
function publish(
uint128 _first_sell_price,
uint8 _royalty_fee,
uint16 _shill_times,
bytes32 _ipfs_hash,
address _token_addr,
bool _is_free,
bool _is_NC,
bool _is_ND
)
external
{
require(_royalty_fee <= 100, "SparkLink: Royalty fee should be <= 100%.");
_issueIds.increment();
require(_issueIds.current() <= type(uint32).max, "SparkLink: Value doesn't fit in 32 bits.");
if (_token_addr != address(0))
require(IERC20(_token_addr).totalSupply() > 0, "Not a valid ERC20 token address");
uint32 new_issue_id = uint32(_issueIds.current());
uint64 rootNFTId = getNftIdByEditionIdAndIssueId(new_issue_id, 1);
require(
_checkOnERC721Received(address(0), msg.sender, rootNFTId, ""),
"SparkLink: Transfer to non ERC721Receiver implementer"
);
Edition storage new_NFT = editions_by_id[rootNFTId];
uint64 information;
information = reWriteUint8InUint64(56, _royalty_fee, information);
information = reWriteUint16InUint64(40, _shill_times, information);
information = reWriteBoolInUint64(37, _is_free, information);
information = reWriteBoolInUint64(38, _is_NC, information);
information = reWriteBoolInUint64(39, _is_ND, information);
information += 1;
token_addresses[new_issue_id] = _token_addr;
new_NFT.father_id = information;
new_NFT.remaining_shill_times = _shill_times;
new_NFT.shill_price = _first_sell_price;
new_NFT.owner = msg.sender;
new_NFT.ipfs_hash = _ipfs_hash;
_balances[msg.sender] += 1;
emit Transfer(address(0), msg.sender, rootNFTId);
emit Publish(
msg.sender,
rootNFTId,
_token_addr
);
}
/**
* @dev Buy a child NFT from the _NFT_id buyer input
*
* Requirements:
*
* - `_NFT_id`: _NFT_id the father NFT id buyer mint NFT from
* remain shill times of the NFT_id you input should greater than 0
* Emits a {Ttansfer} event.
* - Emitted {Transfer} event from 0x0 address to msg.sender, contain new NFT id.
* - New NFT id will be generater by edition id and issue id
* 0~31 edition id
* 32~63 issue id
*/
function acceptShill(
uint64 _NFT_id
)
external
payable
{
require(isEditionExisting(_NFT_id), "SparkLink: This NFT does not exist");
require(editions_by_id[_NFT_id].remaining_shill_times > 0, "SparkLink: There is no remaining shill time for this NFT");
if (!isRootNFT(_NFT_id)||!getIsFreeByNFTId(_NFT_id)){
address token_addr = getTokenAddrByNFTId(_NFT_id);
if (token_addr == address(0)){
require(msg.value == editions_by_id[_NFT_id].shill_price, "SparkLink: Wrong price");
_addProfit( _NFT_id, editions_by_id[_NFT_id].shill_price);
}
else {
uint256 before_balance = IERC20(token_addr).balanceOf(address(this));
IERC20(token_addr).safeTransferFrom(msg.sender, address(this), editions_by_id[_NFT_id].shill_price);
_addProfit( _NFT_id, uint256toUint128(IERC20(token_addr).balanceOf(address(this))-before_balance));
}
}
editions_by_id[_NFT_id].remaining_shill_times -= 1;
_mintNFT(_NFT_id, msg.sender);
if (editions_by_id[_NFT_id].remaining_shill_times == 0)
_mintNFT(_NFT_id, ownerOf(_NFT_id));
}
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `transfer_price` has been set, caller should give same value in msg.sender.
* - Will call `claimProfit` before transfer and `transfer_price` will be set to zero after transfer.
* Emits a {TransferAsset} events
*/
function transferFrom(address from, address to, uint256 tokenId) external payable override {
_transfer(from, to, uint256toUint64(tokenId));
}
function safeTransferFrom(address from, address to, uint256 tokenId) external payable override{
_safeTransfer(from, to, uint256toUint64(tokenId), "");
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata _data) external payable override {
_safeTransfer(from, to, uint256toUint64(tokenId), _data);
}
/**
* @dev Claim profit from reward pool of NFT.
*
* Requirements:
*
* - `_NFT_id`: The NFT id of NFT caller claim, the profit will give to its owner.
* - If its profit is zero the event {Claim} will not be emited.
* Emits a {Claim} events
*/
function claimProfit(uint64 _NFT_id) public {
require(isEditionExisting(_NFT_id), "SparkLink: This edition does not exist");
if (editions_by_id[_NFT_id].profit != 0) {
uint128 amount = editions_by_id[_NFT_id].profit;
address token_addr = getTokenAddrByNFTId(_NFT_id);
if (DAO_fee != 0) {
uint128 DAO_amount = calculateFee(amount, DAO_fee);
amount -= DAO_amount;
if (token_addr == address(0)) {
payable(DAO_router01).transfer(DAO_amount);
}
else if (uniswapV2Factory.getPair(token_addr, uniswapV2Router.WETH()) == address(0)) {
IERC20(token_addr).safeTransfer(DAO_router02,DAO_amount);
}
else {
_swapTokensForEth(token_addr, DAO_amount);
}
}
editions_by_id[_NFT_id].profit = 0;
if (!isRootNFT(_NFT_id)) {
uint128 _royalty_fee = calculateFee(amount, getRoyaltyFeeByNFTId(_NFT_id));
_addProfit(getFatherByNFTId(_NFT_id), _royalty_fee);
amount -= _royalty_fee;
}
if (token_addr == address(0)){
payable(ownerOf(_NFT_id)).transfer(amount);
}
else {
IERC20(token_addr).safeTransfer(ownerOf(_NFT_id), amount);
}
emit Claim(
_NFT_id,
ownerOf(_NFT_id),
amount
);
}
}
/**
* @dev Set token URI.
*
* Requirements:
*
* - `_NFT_id`: transferred token id.
* - `ipfs_hash`: ipfs hash value of the URI will be set.
* Emits a {SetURI} events
*/
function setURI(uint64 _NFT_id, bytes32 ipfs_hash) public {
if (getIsNDByNFTId(_NFT_id)) {
require(_NFT_id == getRootNFTIdByNFTId(_NFT_id), "SparkLink: NFT follows the ND protocol, only the root NFT's URI can be set.");
}
require(ownerOf(_NFT_id) == msg.sender, "SparkLink: Only owner can set the token URI");
_setTokenURI(_NFT_id, ipfs_hash);
}
/**
* @dev update token URI.
*
* Requirements:
*
* - `_NFT_id`: transferred token id.
*/
function updateURI(uint64 _NFT_id) public{
require(ownerOf(_NFT_id) == msg.sender, "SparkLink: Only owner can update the token URI");
editions_by_id[_NFT_id].ipfs_hash = editions_by_id[getRootNFTIdByNFTId(_NFT_id)].ipfs_hash;
}
function label(uint64 _NFT_id, string memory content) public {
require(ownerOf(_NFT_id) == msg.sender, "SparkLink: Only owner can label this NFT");
emit Label(_NFT_id, content);
}
/**
* @dev Determine NFT price before transfer.
*
* Requirements:
*
* - `_NFT_id`: transferred token id.
* - `_price`: The amount of ETH should be payed for `_NFT_id`
* Emits a {DeterminePrice} events
*/
function determinePrice(
uint64 _NFT_id,
uint128 _price
)
public
{
require(isEditionExisting(_NFT_id), "SparkLink: This NFT does not exist");
require(msg.sender == ownerOf(_NFT_id), "SparkLink: Only owner can set the price");
editions_by_id[_NFT_id].transfer_price = _price;
emit DeterminePrice(_NFT_id, _price);
}
/**
* @dev Determine NFT price before transfer.
*
* Requirements:
*
* - `_NFT_id`: transferred token id.
* - `_price`: The amount of ETH should be payed for `_NFT_id`
* - `_to`: The account address `approve` to.
* Emits a {DeterminePriceAndApprove} events
*/
function determinePriceAndApprove(
uint64 _NFT_id,
uint128 _price,
address _to
)
public
{
determinePrice(_NFT_id, _price);
approve(_to, _NFT_id);
emit DeterminePriceAndApprove(_NFT_id, _price, _to);
}
function setDAOFee(uint8 _DAO_fee) public onlyOwner {
require(_DAO_fee <= MAX_DAO_FEE, "SparkLink: DAO fee can not exceed 5%");
emit SetDAOFee(DAO_fee, _DAO_fee);
DAO_fee = _DAO_fee;
}
function setDAORouter01(address _DAO_router01) public onlyOwner {
emit SetDAORouter01(DAO_router01, _DAO_router01);
DAO_router01 = _DAO_router01;
}
function setDAORouter02(address _DAO_router02) public onlyOwner {
emit SetDAORouter01(DAO_router02, _DAO_router02);
DAO_router02 = _DAO_router02;
}
function setUniswapV2Router(address _uniswapV2Router) public onlyOwner {
uniswapV2Router = IUniswapV2Router02(_uniswapV2Router);
}
function setUniswapV2Factory(address _uniswapV2Factory) public onlyOwner {
uniswapV2Factory = IUniswapV2Factory(_uniswapV2Factory);
}
function setLoosRatio(uint8 _loss_ratio) public onlyOwner {
require(_loss_ratio <= MAX_LOSS_RATIO, "SparkLink: Loss ratio can not below 50%");
emit SetLoosRatio(loss_ratio, _loss_ratio);
loss_ratio = _loss_ratio;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "SparkLink: Approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"SparkLink: Approve caller is not owner nor approved for all"
);
_approve(to, uint256toUint64(tokenId));
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "SparkLink: Approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "SparkLink: Balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = editions_by_id[uint256toUint64(tokenId)].owner;
require(owner != address(0), "SparkLink: Owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Query NFT information set.
*
* Requirements:
* - `_NFT_id`: The id of the edition queryed.
* Return :
* - `issue_information`: For root NFT it stores issue abstract sturcture
* - 0~31 `total_amount`
* - 37 `is_free`
* - 38 `is_NC`
* - 39 `is_ND`
* - 40~55 `shill_times`
* - 56~63 `royalty_fee`
* - `father_id`: For root NFT it stores issue abstract sturcture
* For other NFTs its stores the NFT Id of which NFT it `acceptShill` from
* - `shill_price`: The price should be paid when others `accpetShill` from this NFT
* - `remaining_shill_times`: The initial value is the shilltimes of the issue it belongs to
* When others `acceptShill` from this NFT, it will subtract one until its value is 0
* - `owner`: record the owner of this NFT
* - `transfer_price`: The initial value is zero
* Set by `determinePrice` or `determinePriceAndApprove` before `transferFrom`
* It will be checked wether equal to msg.value when `transferFrom` is called
* After `transferFrom` this value will be set to zero
* - `profit`: record the profit owner can claim (include royalty fee it should conduct to its father NFT)
* - `metadata`: IPFS hash value of the URI where this NTF's metadata stores
*/
function getNFTInfoByNFTID(uint64 _NFT_id)
public view
returns (
uint64 issue_information,
uint64 father_id,
uint128 shill_price,
uint16 remain_shill_times,
uint128 profit,
string memory metadata
)
{
require(isEditionExisting(_NFT_id), "SparkLink: Approved query for nonexistent token");
return(
editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id,
getFatherByNFTId(_NFT_id),
editions_by_id[_NFT_id].shill_price,
getRemainShillTimesByNFTId(_NFT_id),
getProfitByNFTId(_NFT_id),
tokenURI(_NFT_id)
);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(isEditionExisting(uint256toUint64(tokenId)), "SparkLink: Approved query for nonexistent token");
return _tokenApprovals[uint256toUint64(tokenId)];
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(isEditionExisting(uint256toUint64(tokenId)), "SparkLink: URI query for nonexistent token");
bytes32 _ipfs_hash = editions_by_id[uint256toUint64(tokenId)].ipfs_hash;
string memory encoded_hash = _toBase58String(_ipfs_hash);
string memory base = _baseURI();
return string(abi.encodePacked(base, encoded_hash));
}
/**
* @dev Query is issue free for first lever buyer.
*
* Requirements:
* - `_NFT_id`: The id of the edition queryed.
* Return a bool value.
*/
function getIsFreeByNFTId(uint64 _NFT_id) public view returns (bool) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
return getBoolFromUint64(37, editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id);
}
/**
* @dev Query is issue follows the NC protocol by any NFT belongs to this issue.
*
* Requirements:
* - `_NFT_id`: The id of the edition queryed.
* Return a bool value.
*/
function getIsNCByNFTId(uint64 _NFT_id) public view returns (bool) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
return getBoolFromUint64(38, editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id);
}
/**
* @dev Query is issue follows the ND protocol by any NFT belongs to this issue.
*
* Requirements:
* - `_NFT_id`: The id of the edition queryed.
* Return a bool value.
*/
function getIsNDByNFTId(uint64 _NFT_id) public view returns (bool) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
return getBoolFromUint64(39, editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id);
}
/**
* @dev Query is edition exist.
*
* Requirements:
* - `_NFT_id`: The id of the edition queryed.
* Return a bool value.
*/
function isEditionExisting(uint64 _NFT_id) public view returns (bool) {
return (editions_by_id[_NFT_id].owner != address(0));
}
/**
* @dev Query the amount of ETH a NFT can be claimed.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return the value this NFT can be claimed.
* If the NFT is not root NFT, this value will subtract royalty fee percent.
*/
function getProfitByNFTId(uint64 _NFT_id) public view returns (uint128){
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
uint128 amount = editions_by_id[_NFT_id].profit;
if (DAO_fee != 0) {
uint128 DAO_amount = calculateFee(amount, DAO_fee);
amount -= DAO_amount;
}
if (!isRootNFT(_NFT_id)) {
uint128 _total_fee = calculateFee(amount, getRoyaltyFeeByNFTId(_NFT_id));
amount -= _total_fee;
}
return amount;
}
/**
* @dev Query royalty fee percent of an issue by any NFT belongs to this issue.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return royalty fee percent of this issue.
*/
function getRoyaltyFeeByNFTId(uint64 _NFT_id) public view returns (uint8) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
return getUint8FromUint64(56, editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id);
}
/**
* @dev Query max shill times of an issue by any NFT belongs to this issue.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return max shill times of this issue.
*/
function getShillTimesByNFTId(uint64 _NFT_id) public view returns (uint16) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
return getUint16FromUint64(40, editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id);
}
/**
* @dev Query total NFT number of a issue by any NFT belongs to this issue.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return total NFT number of this issue.
*/
function getTotalAmountByNFTId(uint64 _NFT_id) public view returns (uint32) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
return getBottomUint32FromUint64(editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id);
}
/**
* @dev Query supported token address of a issue by any NFT belongs to this issue.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return supported token address of this NFT.
* Address 0 represent ETH.
*/
function getTokenAddrByNFTId(uint64 _NFT_id) public view returns (address) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
return token_addresses[uint32(_NFT_id>>32)];
}
/**
* @dev Query the id of this NFT's father NFT.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* - This NFT should exist and not be root NFT.
* Return the father NFT id of this NFT.
*/
function getFatherByNFTId(uint64 _NFT_id) public view returns (uint64) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
if (isRootNFT(_NFT_id)) {
return 0;
}
return editions_by_id[_NFT_id].father_id;
}
/**
* @dev Query transfer_price of this NFT.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return transfer_price of this NFT.
*/
function getTransferPriceByNFTId(uint64 _NFT_id) public view returns (uint128) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
return editions_by_id[_NFT_id].transfer_price;
}
/**
* @dev Query shill_price of this NFT.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return shill_price of this NFT.
*/
function getShillPriceByNFTId(uint64 _NFT_id) public view returns (uint128) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
if (getIsFreeByNFTId(_NFT_id)&&isRootNFT(_NFT_id))
return 0;
else
return editions_by_id[_NFT_id].shill_price;
}
/**
* @dev Query remaining_shill_times of this NFT.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return remaining_shill_times of this NFT.
*/
function getRemainShillTimesByNFTId(uint64 _NFT_id) public view returns (uint16) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
return editions_by_id[_NFT_id].remaining_shill_times;
}
/**
* @dev Query depth of this NFT.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return depth of this NFT.
*/
function getDepthByNFTId(uint64 _NFT_id) public view returns (uint64) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
uint64 depth = 0;
for (depth = 0; !isRootNFT(_NFT_id); _NFT_id = getFatherByNFTId(_NFT_id)) {
depth += 1;
}
return depth;
}
/**
* @dev Query is this NFT is root NFT by check is its edition id is 1.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return a bool value to indicate wether this NFT is root NFT.
*/
function isRootNFT(uint64 _NFT_id) public pure returns (bool) {
return getBottomUint32FromUint64(_NFT_id) == uint32(1);
}
/**
* @dev Query root NFT id by NFT id.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return a bool value to indicate wether this NFT is root NFT.
*/
function getRootNFTIdByNFTId(uint64 _NFT_id) public pure returns (uint64) {
return ((_NFT_id>>32)<<32 | uint64(1));
}
/**
* @dev Query loss ratio of this contract.
*
* Return loss ratio of this contract.
*/
function getLossRatio() public view returns (uint8) {
return loss_ratio;
}
/**
* @dev Calculate edition id by NFT id.
*
* Requirements:
* - `_NFT_id`: The NFT id of the NFT caller want to get.
* Return edition id.
*/
function getEditionIdByNFTId(uint64 _NFT_id) public pure returns (uint32) {
return getBottomUint32FromUint64(_NFT_id);
}
// Token name
string private _name;
// Token symbol
string private _symbol;
uint8 public loss_ratio = 62;
uint8 public DAO_fee = 2;
uint8 public constant MAX_DAO_FEE = 2;
uint8 public constant MAX_LOSS_RATIO = 50;
address public DAO_router01;
address public DAO_router02;
IUniswapV2Router02 public uniswapV2Router;
IUniswapV2Factory public uniswapV2Factory;
// Mapping owner address to token count
mapping(address => uint64) private _balances;
// Mapping from token ID to approved address
mapping(uint64 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
mapping (uint64 => Edition) private editions_by_id;
// mapping from issue ID to support ERC20 token address
mapping(uint32 => address) private token_addresses;
bytes constant private sha256MultiHash = hex"1220";
bytes constant private ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
function _swapTokensForEth(address token_addr, uint128 token_amount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = token_addr;
path[1] = uniswapV2Router.WETH();
IERC20(token_addr).approve(address(uniswapV2Router), token_amount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
token_amount,
0, // accept any amount of ETH
path,
DAO_router01,
block.timestamp
);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint64 tokenId,
bytes memory _data
)
private
returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("SparkLink: Transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint64 tokenId, bytes32 ipfs_hash) internal virtual {
bytes32 old_URI = editions_by_id[tokenId].ipfs_hash;
editions_by_id[tokenId].ipfs_hash = ipfs_hash;
emit SetURI(tokenId, old_URI, ipfs_hash);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param _NFT_id NFT id of father NFT
* @param _owner indicate the address new NFT transfer to
* @return a uint64 store new NFT id
**/
function _mintNFT(
uint64 _NFT_id,
address _owner
)
internal
returns (uint64)
{
_addTotalAmount(_NFT_id);
uint32 new_edition_id = getTotalAmountByNFTId(_NFT_id);
uint64 new_NFT_id = getNftIdByEditionIdAndIssueId(uint32(_NFT_id>>32), new_edition_id);
require(
_checkOnERC721Received(address(0), _owner, new_NFT_id, ""),
"SparkLink: Transfer to non ERC721Receiver implementer"
);
Edition storage new_NFT = editions_by_id[new_NFT_id];
new_NFT.remaining_shill_times = getShillTimesByNFTId(_NFT_id);
new_NFT.father_id = _NFT_id;
if (getIsFreeByNFTId(_NFT_id)&&isRootNFT(_NFT_id))
new_NFT.shill_price = editions_by_id[_NFT_id].shill_price;
else
new_NFT.shill_price = calculateFee(editions_by_id[_NFT_id].shill_price, loss_ratio);
if (new_NFT.shill_price == 0) {
new_NFT.shill_price = editions_by_id[_NFT_id].shill_price;
}
new_NFT.owner = _owner;
new_NFT.ipfs_hash = editions_by_id[_NFT_id].ipfs_hash;
_balances[_owner] += 1;
emit Transfer(address(0), _owner, new_NFT_id);
return new_NFT_id;
}
/**
* @dev Internal function to clear approve and transfer_price
*
* @param _NFT_id NFT id of father NFT
**/
function _afterTokenTransfer (uint64 _NFT_id) internal {
// Clear approvals from the previous owner
_approve(address(0), _NFT_id);
editions_by_id[_NFT_id].transfer_price = 0;
}
/**
* @dev Internal function to support transfer `tokenId` from `from` to `to`.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint64 tokenId
)
internal
virtual
{
require(ownerOf(tokenId) == from, "SparkLink: Transfer of token that is not own");
require(_isApprovedOrOwner(_msgSender(), tokenId), "SparkLink: Transfer caller is not owner nor approved");
require(to != address(0), "SparkLink: Transfer to the zero address");
if (msg.sender != ownerOf(tokenId)) {
address token_addr = getTokenAddrByNFTId(tokenId);
uint128 transfer_price = editions_by_id[tokenId].transfer_price;
if (token_addr == address(0)){
require(msg.value == transfer_price, "SparkLink: Price not met");
_addProfit(tokenId, transfer_price);
}
else {
uint256 before_balance = IERC20(token_addr).balanceOf(address(this));
IERC20(token_addr).safeTransferFrom(msg.sender, address(this), transfer_price);
_addProfit(tokenId, uint256toUint128(IERC20(token_addr).balanceOf(address(this))-before_balance));
}
claimProfit(tokenId);
}
else {
claimProfit(tokenId);
}
_afterTokenTransfer(tokenId);
_balances[from] -= 1;
_balances[to] += 1;
editions_by_id[tokenId].owner = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint64 tokenId,
bytes memory _data
)
internal
virtual
{
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "SparkLink: Transfer to non ERC721Receiver implementer");
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint64 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
function _addProfit(uint64 _NFT_id, uint128 _increase) internal {
editions_by_id[_NFT_id].profit = editions_by_id[_NFT_id].profit+_increase;
}
function _addTotalAmount(uint64 _NFT_Id) internal {
require(getTotalAmountByNFTId(_NFT_Id) < type(uint32).max, "SparkLink: There is no left in this issue.");
editions_by_id[getRootNFTIdByNFTId(_NFT_Id)].father_id += 1;
}
function _isApprovedOrOwner(address spender, uint64 tokenId) internal view virtual returns (bool) {
require(isEditionExisting(tokenId), "SparkLink: Operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
function _baseURI() internal pure returns (string memory) {
return "https://ipfs.io/ipfs/";
}
/**
* @dev Calculate NFT id by issue id and edition id.
*
* Requirements:
* - `_issue_id`: The issue id of the NFT caller want to get.
* - `_edition_id`: The edition id of the NFT caller want to get.
* Return NFT id.
*/
function getNftIdByEditionIdAndIssueId(uint32 _issue_id, uint32 _edition_id) internal pure returns (uint64) {
return (uint64(_issue_id)<<32)|uint64(_edition_id);
}
function getBoolFromUint64(uint8 position, uint64 data64) internal pure returns (bool flag) {
// (((1 << size) - 1) & base >> position)
assembly {
flag := and(1, shr(position, data64))
}
}
function getUint8FromUint64(uint8 position, uint64 data64) internal pure returns (uint8 data8) {
// (((1 << size) - 1) & base >> position)
assembly {
data8 := and(sub(shl(8, 1), 1), shr(position, data64))
}
}
function getUint16FromUint64(uint8 position, uint64 data64) internal pure returns (uint16 data16) {
// (((1 << size) - 1) & base >> position)
assembly {
data16 := and(sub(shl(16, 1), 1), shr(position, data64))
}
}
function getBottomUint32FromUint64(uint64 data64) internal pure returns (uint32 data32) {
// (((1 << size) - 1) & base >> position)
assembly {
data32 := and(sub(shl(32, 1), 1), data64)
}
}
function reWriteBoolInUint64(uint8 position, bool flag, uint64 data64) internal pure returns (uint64 boxed) {
assembly {
// mask = ~((1 << 8 - 1) << position)
// _box = (mask & _box) | ()data << position)
boxed := or( and(data64, not(shl(position, 1))), shl(position, flag))
}
}
function reWriteUint8InUint64(uint8 position, uint8 flag, uint64 data64) internal pure returns (uint64 boxed) {
assembly {
// mask = ~((1 << 8 - 1) << position)
// _box = (mask & _box) | ()data << position)
boxed := or(and(data64, not(shl(position, 1))), shl(position, flag))
}
}
function reWriteUint16InUint64(uint8 position, uint16 data16, uint64 data64) internal pure returns (uint64 boxed) {
assembly {
// mask = ~((1 << 16 - 1) << position)
// _box = (mask & _box) | ()data << position)
boxed := or( and(data64, not(shl(position, sub(shl(16, 1), 1)))), shl(position, data16))
}
}
function uint256toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SparkLink: Value doesn't fit in 64 bits");
return uint64(value);
}
function uint256toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SparkLink: Value doesn't fit in 128 bits");
return uint128(value);
}
function calculateFee(uint128 _amount, uint8 _fee_percent) internal pure returns (uint128) {
return _amount*_fee_percent/10**2;
}
function _toBase58String(bytes32 con) internal pure returns (string memory) {
bytes memory source = bytes.concat(sha256MultiHash,con);
uint8[] memory digits = new uint8[](64); //TODO: figure out exactly how much is needed
digits[0] = 0;
uint8 digitlength = 1;
for (uint256 i = 0; i<source.length; ++i) {
uint carry = uint8(source[i]);
for (uint256 j = 0; j<digitlength; ++j) {
carry += uint(digits[j]) * 256;
digits[j] = uint8(carry % 58);
carry = carry / 58;
}
while (carry > 0) {
digits[digitlength] = uint8(carry % 58);
digitlength++;
carry = carry / 58;
}
}
//return digits;
return string(toAlphabet(reverse(truncate(digits, digitlength))));
}
function toAlphabet(uint8[] memory indices) internal pure returns (bytes memory) {
bytes memory output = new bytes(indices.length);
for (uint256 i = 0; i<indices.length; i++) {
output[i] = ALPHABET[indices[i]];
}
return output;
}
function truncate(uint8[] memory array, uint8 length) internal pure returns (uint8[] memory) {
uint8[] memory output = new uint8[](length);
for (uint256 i = 0; i<length; i++) {
output[i] = array[i];
}
return output;
}
function reverse(uint8[] memory input) internal pure returns (uint8[] memory) {
uint8[] memory output = new uint8[](input.length);
for (uint256 i = 0; i<input.length; i++) {
output[i] = input[input.length-1-i];
}
return output;
}
}
|
Query total NFT number of a issue by any NFT belongs to this issue. Requirements: - `_NFT_id`: The id of the NFT queryed. Return total NFT number of this issue./
|
function getTotalAmountByNFTId(uint64 _NFT_id) public view returns (uint32) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
return getBottomUint32FromUint64(editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id);
}
| 1,067,850 |
./full_match/100/0x62D007D4c4Db781C24FF6ac19279B9A9Ec32b344/sources/contracts/recover/recover.sol
|
Pay the arbitration fee to raise a dispute. To be called by the owner. UNTRUSTED. Note that the arbitrator can have createDispute throw, which will make this function throw and therefore lead to a party being timed-out. This is not a vulnerability as the arbitrator can rule in favor of one party anyway. _claimID The index of the claim./ Require that the total paid to be at least the arbitration cost. The finder still has to pay. This can also happen if he has paid, but arbitrationCost has increased.
|
function payArbitrationFeeByOwner(uint _claimID) public payable {
Claim storage itemClaim = claims[_claimID];
Item storage item = items[itemClaim.itemID];
uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
require(
itemClaim.status < Status.DisputeCreated,
"Dispute has already been created or because the transaction of the item has been executed."
);
require(item.owner == _msgSender(), "The caller must be the owner of the item.");
require(true == itemClaim.isAccepted, "The claim of the item must be accepted.");
item.ownerFee += msg.value;
require(item.ownerFee >= arbitrationCost, "The owner fee must cover arbitration costs.");
itemClaim.lastInteraction = block.timestamp;
if (itemClaim.finderFee < arbitrationCost) {
itemClaim.status = Status.WaitingFinder;
emit HasToPayFee(_claimID, Party.Finder);
raiseDispute(_claimID, arbitrationCost);
}
}
| 14,273,933 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
import "../shared/CoreController.sol";
import "@gif-interface/contracts/modules/IAccess.sol";
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
contract AccessController is
IAccess,
CoreController,
AccessControlEnumerable
{
// 0xe984cfd1d1fa34f80e24ddb2a60c8300359d79eee44555bc35c106eb020394cd
bytes32 public constant PRODUCT_OWNER_ROLE = keccak256("PRODUCT_OWNER_ROLE");
// 0xd26b4cd59ffa91e4599f3d18b02fcd5ffb06e03216f3ee5f25f68dc75cbbbaa2
bytes32 public constant ORACLE_PROVIDER_ROLE = keccak256("ORACLE_PROVIDER_ROLE");
// 0x3c4cdb47519f2f89924ebeb1ee7a8a43b8b00120826915726460bb24576012fd
bytes32 public constant RISKPOOL_KEEPER_ROLE = keccak256("RISKPOOL_KEEPER_ROLE");
mapping(bytes32 => bool) public validRole;
bool defaultAdminSet;
function _afterInitialize() internal override {
_populateValidRoles();
}
// IMPORTANT this method must be called during initial setup of the GIF instance
// otherwise any caller might set the default role admin to any addressS
function setDefaultAdminRole(address defaultAdmin)
public
{
require(!defaultAdminSet, "ERROR:ACL-001:ADMIN_ROLE_ALREADY_SET");
defaultAdminSet = true;
_setupRole(DEFAULT_ADMIN_ROLE, defaultAdmin);
}
//--- enforce role ownership --------------------------------------------//
function enforceProductOwnerRole(address principal) public view {
enforceRole(PRODUCT_OWNER_ROLE, principal);
}
function enforceOracleProviderRole(address principal) public view {
enforceRole(ORACLE_PROVIDER_ROLE, principal);
}
function enforceRiskpoolKeeperRole(address principal) public view {
enforceRole(RISKPOOL_KEEPER_ROLE, principal);
}
// adapted from oz AccessControl._checkRole
function enforceRole(bytes32 role, address principal) public view {
require(
hasRole(role, principal),
string(
abi.encodePacked(
"AccessController.enforceRole: account ",
Strings.toHexString(uint160(principal), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
//--- manage role ownership ---------------------------------------------//
function grantRole(bytes32 role, address principal)
public
override(AccessControl, IAccessControl, IAccess)
onlyInstanceOperator
{
require(validRole[role], "ERROR:ACL-002:ROLE_UNKNOWN_OR_INVALID");
AccessControl.grantRole(role, principal);
}
function revokeRole(bytes32 role, address principal)
public
override(AccessControl, IAccessControl, IAccess)
onlyInstanceOperator
{
AccessControl.revokeRole(role, principal);
}
function renounceRole(bytes32 role, address principal)
public
override(AccessControl, IAccessControl, IAccess)
{
AccessControl.renounceRole(role, principal);
}
//--- manage roles ------------------------------------------------------//
function addRole(bytes32 role)
public
onlyInstanceOperator
{
require(validRole[role], "ERROR:ACL-003:ROLE_EXISTING_AND_VALID");
validRole[role] = true;
}
function invalidateRole(bytes32 role)
public
onlyInstanceOperator
{
require(validRole[role], "ERROR:ACL-004:ROLE_UNKNOWN_OR_INVALID");
validRole[role] = false;
}
function hasRole(bytes32 role, address principal)
public view
override(AccessControl, IAccessControl, IAccess)
returns(bool)
{
return super.hasRole(role, principal);
}
function productOwnerRole() public view override returns(bytes32) {
return PRODUCT_OWNER_ROLE;
}
function oracleProviderRole() public view override returns(bytes32) {
return ORACLE_PROVIDER_ROLE;
}
function riskpoolKeeperRole() public view override returns(bytes32) {
return RISKPOOL_KEEPER_ROLE;
}
function _populateValidRoles() private {
validRole[PRODUCT_OWNER_ROLE] = true;
validRole[ORACLE_PROVIDER_ROLE] = true;
validRole[RISKPOOL_KEEPER_ROLE] = true;
}
}
|
--- manage roles ------------------------------------------------------
|
function addRole(bytes32 role)
public
onlyInstanceOperator
{
require(validRole[role], "ERROR:ACL-003:ROLE_EXISTING_AND_VALID");
validRole[role] = true;
}
| 12,590,464 |
./full_match/80001/0xC031277cfa6C43bF56E694bfe76eEC58454dF677/sources/contracts/dao/ERC1155Dao.sol
|
allows token owner to list a token for lending. emits the Lending event. Requirements: ‼ contract should not be paused. ‼ caller must be the owner of the the token `tokenId + serialNo`. ‼ token with `tokenId + serialNo` must not be already listed for auction or fixed price. ‼ token with `tokenId + serialNo` must not be already listed for lending. ‼ token with `tokenId + serialNo` must be active. ‼ `lendingPeriod` must be multiple of day and must atleast 3 days. ‼ lending cannot be held before all tokens from contract are sold. ‼ token with `tokenId` must not be expired. ‼ token with `tokenId + serialNo` life must be enough. ‼ `amount` should be within a given range. Signature for listForLending(string,uint256,uint32,uint104) : `0x3f3d3e39` tokenId id of the token being listed for lending. serialNo serial Number of the token. lendingPeriod timestamp for number of days for which auction will run. amount timestamp for number of days for which auction will run./
|
function listForLending(
uint256 tokenId,
uint256 serialNo,
uint32 lendingPeriod,
uint104 amount
) external whenNotPaused {
TokenBearer memory tokenOwner = _tokenBearer[tokenId][serialNo];
if (tokenOwner.user != msg.sender) revert NotAvailableForOperation(1);
if (tokenOwner.fixedOrAuction != 0) revert NotAvailableForOperation(15);
if (tokenOwner.lendingStatus) revert NotAvailableForOperation(16);
if (!tokenOwner.isActivated) revert NotAvailableForOperation(9);
if (
lendingPeriod > 0 &&
lendingPeriod % 86400 == 0 &&
lendingPeriod >= 259200
) revert NotAvailableForOperation(10);
if (_balances[tokenId][address(this)] != 0)
revert NotAvailableForOperation(7);
TokenDetails memory tokenDet = _tokenDetails[tokenId];
_checkforExpired(
tokenOwner.startOfLife,
tokenDet.expireOn,
lendingPeriod,
tokenOwner.endOfLife
);
uint256 lendingPrice;
uint256 lendingPriceFloor;
uint256 lendingPriceCeil;
unchecked {
lendingPrice = (tokenDet.tokenPrice / 100) * 98;
(lendingPriceFloor, lendingPriceCeil) = (
lendingPrice / 1000 + _platformFeesInWei,
lendingPrice / 10 + _platformFeesInWei
);
}
if (amount < lendingPriceFloor && amount > lendingPriceCeil)
revert NotAvailableForOperation(6);
_tokenBearer[tokenId][serialNo] = TokenBearer({
user: tokenOwner.user,
startOfLife: tokenOwner.startOfLife,
endOfLife: tokenOwner.endOfLife,
borrower: address(0),
lendingStartTimestamp: uint48(block.timestamp),
borrowingStartTimestamp: 0,
bidStartingPrice: 0,
biddingLife: 0,
listingPrice: 0,
lendingStatus: true,
lendingPeriod: lendingPeriod,
borrowingPeriod: 0,
lendingPricePerDay: amount,
fixedOrAuction: 0,
isActivated: tokenOwner.isActivated
});
emit Lending(tokenId, serialNo, true, block.timestamp);
}
| 5,574,294 |
./partial_match/1/0x71616E8C62aDF18C0645188AE04b90b446a860A7/sources/src/TokenTapas.sol
|
Checks if this or the parent contract supports an interface by its ID. _interfaceId The ID of the interface. return Returns `true` if the interface is supported.
|
function supportsInterface(bytes4 _interfaceId) public view virtual override returns (bool) {
return
_interfaceId == type(IERC20).interfaceId ||
_interfaceId == type(IERC721).interfaceId ||
_interfaceId == type(IVotes).interfaceId ||
super.supportsInterface(_interfaceId);
}
| 4,078,682 |
./full_match/84531/0xB09E02a9bC0f8DB9aE4c7ca9e3dDDE621bE16734/sources/contracts/libraries/Clones.sol
|
Computes the address of a clone deployed using {Clones-cloneDeterministic}./
|
function predictDeterministicAddress(address implementation, bytes32 salt)
internal
view
returns (address predicted)
{
return predictDeterministicAddress(implementation, salt, address(this));
}
| 11,522,051 |
// SPDX-License-Identifier: MIT
pragma solidity ^ 0.7.0;
contract BulkTokenTransfer {
/* This contract is still in beta. Use this contract at your own risk */
// Public variable; owns this contract
address public owner;
// Event which stores details of each individual transfer
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
// Constructor which sets the public variable (owner) to the external account address who deployed this contract
constructor() {
owner = msg.sender;
}
// Modifier to ensure only the owner can perform certain function calls
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
// Given 100 external account addresses and 100 corresponding amounts in wei; Perform 100 transfers (as internal tx)
function bulkSendEth(address payable[100] memory addresses, uint256[100] memory amounts) public payable onlyOwner returns(bool success) {
/* This contract is still in beta. Use this contract at your own risk */
// transfer to each address
for (uint8 iter = 0; iter < 100; iter++) {
if((addresses[iter] != address(0)) && (amounts[iter] * 1 wei) != 0){
addresses[iter].transfer(amounts[iter] * 1 wei);
emit Transfer(msg.sender, addresses[iter], amounts[iter] * 1 wei);
}
}
return true;
}
// Check balance of any external account
function getbalance(address addr) public view returns(uint value) {
/* This contract is still in beta. Use this contract at your own risk */
return addr.balance;
}
// Allow the owner of the contract to withdraw any left over network tokens
function withdrawEther(address payable addr, uint amount) public onlyOwner returns(bool success) {
/* This contract is still in beta. Use this contract at your own risk */
addr.transfer(amount * 1 wei);
return true;
}
// Allow the owner to destroy the contract and subsequently receive any left over network tokens
function destroy(address payable _to) public onlyOwner {
/* This contract is still in beta. Use this contract at your own risk */
selfdestruct(_to);
}
}
|
Allow the owner of the contract to withdraw any left over network tokens
|
function withdrawEther(address payable addr, uint amount) public onlyOwner returns(bool success) {
addr.transfer(amount * 1 wei);
return true;
| 967,760 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
import "./Proxy.sol";
interface ERC165 {
function supportsInterface(bytes4 id) external view returns (bool);
}
///@notice Proxy implementing EIP173 for ownership management
contract EIP173Proxy is Proxy {
// ////////////////////////// EVENTS ///////////////////////////////////////////////////////////////////////
event ProxyAdminTransferred(
address indexed previousAdmin,
address indexed newAdmin
);
// /////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////////////
constructor(
address implementationAddress,
address adminAddress,
bytes memory data
) payable {
_setImplementation(implementationAddress, data);
_setProxyAdmin(adminAddress);
}
// ///////////////////// EXTERNAL ///////////////////////////////////////////////////////////////////////////
function proxyAdmin() external view returns (address) {
return _proxyAdmin();
}
function supportsInterface(bytes4 id) external view returns (bool) {
if (id == 0x01ffc9a7 || id == 0x7f5828d0) {
return true;
}
if (id == 0xFFFFFFFF) {
return false;
}
ERC165 implementation;
// solhint-disable-next-line security/no-inline-assembly
assembly {
implementation := sload(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc
)
}
// Technically this is not standard compliant as ERC-165 require 30,000 gas which that call cannot ensure
// because it is itself inside `supportsInterface` that might only get 30,000 gas.
// In practise this is unlikely to be an issue.
try implementation.supportsInterface(id) returns (bool support) {
return support;
} catch {
return false;
}
}
function transferProxyAdmin(address newAdmin) external onlyProxyAdmin {
_setProxyAdmin(newAdmin);
}
function upgradeTo(address newImplementation) external onlyProxyAdmin {
_setImplementation(newImplementation, "");
}
function upgradeToAndCall(address newImplementation, bytes calldata data)
external
payable
onlyProxyAdmin
{
_setImplementation(newImplementation, data);
}
// /////////////////////// MODIFIERS ////////////////////////////////////////////////////////////////////////
modifier onlyProxyAdmin() {
require(msg.sender == _proxyAdmin(), "NOT_AUTHORIZED");
_;
}
// ///////////////////////// INTERNAL //////////////////////////////////////////////////////////////////////
function _proxyAdmin() internal view returns (address adminAddress) {
// solhint-disable-next-line security/no-inline-assembly
assembly {
adminAddress := sload(
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103
)
}
}
function _setProxyAdmin(address newAdmin) internal {
address previousAdmin = _proxyAdmin();
// solhint-disable-next-line security/no-inline-assembly
assembly {
sstore(
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103,
newAdmin
)
}
emit ProxyAdminTransferred(previousAdmin, newAdmin);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
// EIP-1967
abstract contract Proxy {
// /////////////////////// EVENTS ///////////////////////////////////////////////////////////////////////////
event ProxyImplementationUpdated(
address indexed previousImplementation,
address indexed newImplementation
);
// ///////////////////// EXTERNAL ///////////////////////////////////////////////////////////////////////////
// prettier-ignore
receive() external payable virtual {
revert("ETHER_REJECTED"); // explicit reject by default
}
fallback() external payable {
_fallback();
}
// ///////////////////////// INTERNAL //////////////////////////////////////////////////////////////////////
function _fallback() internal {
// solhint-disable-next-line security/no-inline-assembly
assembly {
let implementationAddress := sload(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc
)
calldatacopy(0x0, 0x0, calldatasize())
let success := delegatecall(
gas(),
implementationAddress,
0x0,
calldatasize(),
0,
0
)
let retSz := returndatasize()
returndatacopy(0, 0, retSz)
switch success
case 0 {
revert(0, retSz)
}
default {
return(0, retSz)
}
}
}
function _setImplementation(address newImplementation, bytes memory data)
internal
{
address previousImplementation;
// solhint-disable-next-line security/no-inline-assembly
assembly {
previousImplementation := sload(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc
)
}
// solhint-disable-next-line security/no-inline-assembly
assembly {
sstore(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc,
newImplementation
)
}
emit ProxyImplementationUpdated(
previousImplementation,
newImplementation
);
if (data.length > 0) {
(bool success, ) = newImplementation.delegatecall(data);
if (!success) {
assembly {
// This assembly ensure the revert contains the exact string data
let returnDataSize := returndatasize()
returndatacopy(0, 0, returnDataSize)
revert(0, returnDataSize)
}
}
}
}
}
|
solhint-disable-next-line security/no-inline-assembly
|
function _setProxyAdmin(address newAdmin) internal {
address previousAdmin = _proxyAdmin();
assembly {
sstore(
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103,
newAdmin
)
}
emit ProxyAdminTransferred(previousAdmin, newAdmin);
}
| 1,573,879 |
pragma solidity ^0.5.11;
contract GuarantorManager{
// Contract properties
address payable public administrator;
address[] private guarantors;
// Mappings
mapping(address => bool) public isGuarantor;
// Events
event GuarantorAdded(
address indexed _guarantorAddress
);
event GuarantorDeleted(
address indexed _guarantorAddress
);
// Contract constructor
constructor() public{
administrator = msg.sender;
}
// Self destruction
function destroyContract() public IsAdministrator{
selfdestruct(administrator);
}
/* Function to add a new guarantor
Parameters:
address _guarantor - Address of the guarantor to add
*/
function addGuarantor(address _guarantor) public IsAdministrator {
// Make sure address passed is not already a manager
require(isGuarantor[_guarantor] == false, "Address is already a guarantor");
isGuarantor[_guarantor] = true;
guarantors.push(_guarantor);
emit GuarantorAdded(_guarantor);
}
/* Function to remove a guarantor
Parameters
address _guarantor - Address of the guarantor to be removed
*/
function removeGuarantor(address _guarantor) public IsAdministrator {
// Make sure address passed is actually a guarantor
require(isGuarantor[_guarantor] == true, "Address is not a guarantor");
isGuarantor[_guarantor] = false;
// Delete guarantor from array of all guarantors
uint guarantorCount = guarantors.length;
for(uint i = 0; i < guarantorCount; i++){
if(guarantors[i] == _guarantor){
delete guarantors[i];
break;
}
}
emit GuarantorDeleted(_guarantor);
}
// Function to get all the guarantorsz
function getGuarantors() public view returns(address[] memory) {
return guarantors;
}
// Modifier to check of message sender is the administrator
modifier IsAdministrator(){
require((administrator == msg.sender), "Only Administrators Are Able To Run This Function");
_;
}
}
|
Function to get all the guarantorsz
|
function getGuarantors() public view returns(address[] memory) {
return guarantors;
}
| 882,256 |
./full_match/80001/0x68938d1f6B0657c95c75d589c16C4109FE1Aa7AD/sources/feature-v2/CentralizedAppealableArbitrator.sol
|
Appeals a ruling. _disputeID The ID of the dispute. _extraData Additional info about the appeal./
|
function appeal(uint256 _disputeID, bytes calldata _extraData)
public
payable
override
requireAppealFee(_disputeID, _extraData)
{
super.appeal(_disputeID, _extraData);
DisputeStruct storage dispute = disputes[_disputeID];
dispute.isAppealed = true;
}
| 9,440,830 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {AccessControlEnumerableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {IAaveLendingPool} from "../Aave/interfaces/IAaveLendingPool.sol";
import {IAaveIncentivesController} from "../Aave/interfaces/IAaveIncentivesController.sol";
import {IStakedToken} from "../Aave/interfaces/IStakedToken.sol";
import {IBNPLBankNode} from "./interfaces/IBNPLBankNode.sol";
import {IBNPLNodeStakingPool} from "./interfaces/IBNPLNodeStakingPool.sol";
import {IBNPLSwapMarket} from "../SwapMarket/interfaces/IBNPLSwapMarket.sol";
import {IMintableBurnableTokenUpgradeable} from "../ERC20/interfaces/IMintableBurnableTokenUpgradeable.sol";
import {IBankNodeManager} from "../Management/BankNodeManager.sol";
import {BNPLKYCStore} from "../Management/BNPLKYCStore.sol";
import {TransferHelper} from "../Utils/TransferHelper.sol";
import {BankNodeUtils} from "./lib/BankNodeUtils.sol";
/// @title BNPL BankNode contract
///
/// @notice
/// - Features:
/// **Deposit USDT**
/// **Withdraw USDT**
/// **Donate USDT**
/// **Loan request**
/// **Loan approval/rejected**
/// **Deposit USDT to AAVE**
/// **Withdraw USDT from AAVE**
/// **Claim stkAAVE**
/// **Repayment:**
/// **Swap 20% USDT interests to BNPL in Sushiswap for bonder and staker interest**
/// **Reportoverdue:**
/// **Swap BNPL to USDT in Sushiswap for the slashing functionPlatform**
/// **Claim bank node rewards**
/// @author BNPL
contract BNPLBankNode is Initializable, AccessControlEnumerableUpgradeable, ReentrancyGuardUpgradeable, IBNPLBankNode {
/// @dev Emitted when user `user` is adds `depositAmount` of liquidity while receiving `issueAmount` of pool tokens
event LiquidityAdded(address indexed user, uint256 depositAmount, uint256 poolTokensIssued);
/// @dev Emitted when user `user` burns `withdrawAmount` of pool tokens while receiving `issueAmount` of pool tokens
event LiquidityRemoved(address indexed user, uint256 withdrawAmount, uint256 poolTokensConsumed);
/// @dev Emitted when user `user` donates `donationAmount` of base liquidity tokens to the pool
event Donation(address indexed user, uint256 donationAmount);
/// @dev Emitted when user `user` requests a loan of `loanAmount` with a loan request id of loanRequestId
event LoanRequested(address indexed borrower, uint256 loanAmount, uint256 loanRequestId, string uuid);
/// @dev Emitted when a node manager `operator` denies a loan request with id `loanRequestId`
event LoanDenied(address indexed borrower, uint256 loanRequestId, address operator);
/// @dev Emitted when a node manager `operator` approves a loan request with id `loanRequestId`
event LoanApproved(
address indexed borrower,
uint256 loanRequestId,
uint256 loanId,
uint256 loanAmount,
address operator
);
/// @dev Emitted when user `borrower` makes a payment on the loan request with id `loanRequestId`
event LoanPayment(address indexed borrower, uint256 loanId, uint256 paymentAmount);
struct LoanRequest {
address borrower;
uint256 loanAmount;
uint64 totalLoanDuration;
uint32 numberOfPayments;
uint256 amountPerPayment;
uint256 interestRatePerPayment;
uint8 status; // 0 = under review, 1 = rejected, 2 = cancelled, 3 = *unused for now*, 4 = approved
uint64 statusUpdatedAt;
address statusModifiedBy;
uint256 interestRate;
uint256 loanId;
uint8 messageType; // 0 = plain text, 1 = encrypted with the public key
string message;
string uuid;
}
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
bytes32 public constant OPERATOR_ADMIN_ROLE = keccak256("OPERATOR_ADMIN_ROLE");
uint256 public constant UNUSED_FUNDS_MIN_DEPOSIT_SIZE = 1;
/// @notice The min loan duration (secs)
uint256 public constant MIN_LOAN_DURATION = 30 days;
/// @notice The min loan payment interval (secs)
uint256 public constant MIN_LOAN_PAYMENT_INTERVAL = 2 days;
/// @notice The max loan duration (secs)
uint256 public constant MAX_LOAN_DURATION = 1825 days;
/// @notice The max loan payment interval (secs)
uint256 public constant MAX_LOAN_PAYMENT_INTERVAL = 180 days;
uint32 public constant LENDER_NEEDS_KYC = 1 << 1;
uint32 public constant BORROWER_NEEDS_KYC = 1 << 2;
/// @dev `5192296858534827628530496329219840` wei
uint256 public constant MAX_LOAN_AMOUNT = 0xFFFFFFFFFFFFFFFFFFFFFFFFFF00;
/// @dev `100000000` wei
uint256 public constant MIN_LOAN_AMOUNT = 0x5f5e100;
/// @notice Liquidity token contract (ex. USDT)
IERC20 public override baseLiquidityToken;
/// @notice Pool liquidity token contract (ex. Pool USDT)
IMintableBurnableTokenUpgradeable public override poolLiquidityToken;
/// @notice BNPL token contract
IERC20 public bnplToken;
/// @dev Lending mode (1)
uint16 public override unusedFundsLendingMode;
/// @notice AAVE lending pool contract address
IAaveLendingPool public override unusedFundsLendingContract;
/// @notice AAVE tokens contract
IERC20 public override unusedFundsLendingToken;
/// @notice AAVE incentives controller contract
IAaveIncentivesController public override unusedFundsIncentivesController;
/// @notice The configured lendable token swap market contract (ex. SushiSwap Router)
IBNPLSwapMarket public override bnplSwapMarket;
/// @notice The configured swap market fee
uint24 public override bnplSwapMarketPoolFee;
/// @notice The id of bank node
uint32 public override bankNodeId;
/// @notice The staking pool proxy contract
IBNPLNodeStakingPool public override nodeStakingPool;
/// @notice The bank node manager proxy contract
IBankNodeManager public override bankNodeManager;
/// @notice Liquidity token (ex. USDT) balance of this
uint256 public override baseTokenBalance;
/// @notice The balance of bank node admin
uint256 public override nodeOperatorBalance;
/// @notice Accounts receivable from loans
uint256 public override accountsReceivableFromLoans;
/// @notice Pool liquidity tokens (ex. Pool USDT) circulating
uint256 public override poolTokensCirculating;
/// @notice Current loan request index (pending)
uint256 public override loanRequestIndex;
/// @notice Number of loans in progress
uint256 public override onGoingLoanCount;
/// @notice Current loan index (approved)
uint256 public override loanIndex;
/// @notice The total amount of all activated loans
uint256 public override totalAmountOfActiveLoans;
/// @notice The total amount of all loans
uint256 public override totalAmountOfLoans;
/// @notice [Loan request id] => [Loan request]
mapping(uint256 => LoanRequest) public override loanRequests;
/// @notice [Loan id] => [Loan]
mapping(uint256 => Loan) public override loans;
/// @notice [Loan id] => [Interest paid for]
mapping(uint256 => uint256) public override interestPaidForLoan;
/// @notice The total loss amount of bank node
uint256 public override totalLossAllTime;
/// @notice The total number of loans defaulted
uint256 public override totalLoansDefaulted;
/// @notice The total amount of net earnings
uint256 public override netEarnings;
/// @notice Cumulative value of donate amounts
uint256 public override totalDonatedAllTime;
/// @notice The corresponding id in the BNPL KYC store
uint32 public override kycDomainId;
/// @notice The BNPL KYC store contract
BNPLKYCStore public override bnplKYCStore;
/// @notice Get bank node KYC mode
/// @return kycMode
function kycMode() external view override returns (uint256) {
return bnplKYCStore.domainKycMode(kycDomainId);
}
/// @notice Get bank node KYC public key
/// @return nodeKycPublicKey
function nodePublicKey() external view override returns (address) {
return bnplKYCStore.publicKeys(kycDomainId);
}
/// @dev BankNode contract is created and initialized by the BankNodeManager contract
///
/// - This contract is called through the proxy.
///
/// @param bankNodeInitConfig BankNode configuration (passed in by BankNodeManager contract)
///
/// `BankNodeInitializeArgsV1` paramerter structure:
///
/// ```solidity
/// uint32 bankNodeId // The id of bank node
/// uint24 bnplSwapMarketPoolFee // The configured swap market fee
/// address bankNodeManager // The address of bank node manager
/// address operatorAdmin // The admin with `OPERATOR_ADMIN_ROLE` role
/// address operator // The admin with `OPERATOR_ROLE` role
/// uint256 bnplToken // BNPL token address
/// address bnplSwapMarket // The swap market contract (ex. Sushiswap Router)
/// uint16 unusedFundsLendingMode // Lending mode (1)
/// address unusedFundsLendingContract // Lending contract (ex. AAVE lending pool)
/// address unusedFundsLendingToken // (ex. AAVE aTokens)
/// address unusedFundsIncentivesController // (ex. AAVE incentives controller)
/// address nodeStakingPool // The staking pool of bank node
/// address baseLiquidityToken // Liquidity token contract (ex. USDT)
/// address poolLiquidityToken // Pool liquidity token contract (ex. Pool USDT)
/// address nodePublicKey // Bank node KYC public key
/// uint32 // kycMode Bank node KYC mode
/// ```
function initialize(BankNodeInitializeArgsV1 calldata bankNodeInitConfig)
external
override
nonReentrant
initializer
{
require(
bankNodeInitConfig.unusedFundsLendingMode == 1,
"unused funds lending mode currently only supports aave (1)"
);
__Context_init_unchained();
__ReentrancyGuard_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
baseLiquidityToken = IERC20(bankNodeInitConfig.baseLiquidityToken);
poolLiquidityToken = IMintableBurnableTokenUpgradeable(bankNodeInitConfig.poolLiquidityToken);
bnplToken = IERC20(bankNodeInitConfig.bnplToken);
unusedFundsLendingMode = bankNodeInitConfig.unusedFundsLendingMode;
unusedFundsLendingToken = IERC20(bankNodeInitConfig.unusedFundsLendingToken);
unusedFundsLendingContract = IAaveLendingPool(bankNodeInitConfig.unusedFundsLendingContract);
unusedFundsIncentivesController = IAaveIncentivesController(bankNodeInitConfig.unusedFundsIncentivesController);
bnplSwapMarket = IBNPLSwapMarket(bankNodeInitConfig.bnplSwapMarket);
nodeStakingPool = IBNPLNodeStakingPool(bankNodeInitConfig.nodeStakingPool);
bankNodeManager = IBankNodeManager(bankNodeInitConfig.bankNodeManager);
bnplSwapMarketPoolFee = bankNodeInitConfig.bnplSwapMarketPoolFee;
bankNodeId = bankNodeInitConfig.bankNodeId;
if (bankNodeInitConfig.operator != address(0)) {
_setupRole(OPERATOR_ROLE, bankNodeInitConfig.operator);
}
if (bankNodeInitConfig.operatorAdmin != address(0)) {
_setupRole(OPERATOR_ADMIN_ROLE, bankNodeInitConfig.operatorAdmin);
_setRoleAdmin(OPERATOR_ROLE, OPERATOR_ADMIN_ROLE);
}
bnplKYCStore = bankNodeManager.bnplKYCStore();
kycDomainId = bnplKYCStore.createNewKYCDomain(
address(this),
bankNodeInitConfig.nodePublicKey,
bankNodeInitConfig.kycMode
);
}
/// @notice Returns incentives controller reward token (ex. stkAAVE)
/// @return stakedAAVE
function rewardToken() public view override returns (IStakedToken) {
return IStakedToken(unusedFundsIncentivesController.REWARD_TOKEN());
}
/// @notice Returns `unusedFundsLendingToken` (ex. AAVE aTokens) balance of this
/// @return unusedFundsLendingTokenBalance AAVE aTokens balance of this
function getValueOfUnusedFundsLendingDeposits() public view override returns (uint256) {
return unusedFundsLendingToken.balanceOf(address(this));
}
/// @notice Returns total assets value of bank node
/// @return poolTotalAssetsValue
function getPoolTotalAssetsValue() public view override returns (uint256) {
return baseTokenBalance + getValueOfUnusedFundsLendingDeposits() + accountsReceivableFromLoans;
}
/// @notice Returns total liquidity assets value of bank node (Exclude `accountsReceivableFromLoans`)
/// @return poolTotalLiquidAssetsValue
function getPoolTotalLiquidAssetsValue() public view override returns (uint256) {
return baseTokenBalance + getValueOfUnusedFundsLendingDeposits();
}
/// @notice Pool deposit conversion
///
/// @param depositAmount Liquidity token (ex. USDT) amount
/// @return poolDepositConversion
function getPoolDepositConversion(uint256 depositAmount) public view returns (uint256) {
uint256 poolTotalAssetsValue = getPoolTotalAssetsValue();
return (depositAmount * poolTokensCirculating) / (poolTotalAssetsValue > 0 ? poolTotalAssetsValue : 1);
}
/// @notice Pool withdraw conversion
///
/// @param withdrawAmount Pool liquidity token (ex. pUSDT) amount
/// @return poolWithdrawConversion
function getPoolWithdrawConversion(uint256 withdrawAmount) public view returns (uint256) {
return (withdrawAmount * getPoolTotalAssetsValue()) / (poolTokensCirculating > 0 ? poolTokensCirculating : 1);
}
/// @notice Returns next due timestamp of loan `loanId`
///
/// @param loanId The id of loan
/// @return loanNextDueDate Next due timestamp
function getLoanNextDueDate(uint256 loanId) public view returns (uint64) {
Loan memory loan = loans[loanId];
require(loan.loanStartedAt > 0 && loan.numberOfPaymentsMade < loan.numberOfPayments);
uint256 nextPaymentDate = ((uint256(loan.numberOfPaymentsMade + 1) * uint256(loan.totalLoanDuration)) /
uint256(loan.numberOfPayments)) + uint256(loan.loanStartedAt);
return uint64(nextPaymentDate);
}
/// @dev Withdraw `amount` of base liquidity token from lending contract to this
function _withdrawFromAaveToBaseBalance(uint256 amount) private {
require(amount != 0, "amount cannot be 0");
uint256 ourAaveBalance = unusedFundsLendingToken.balanceOf(address(this));
require(amount <= ourAaveBalance, "amount exceeds aave balance!");
unusedFundsLendingContract.withdraw(address(baseLiquidityToken), amount, address(this));
baseTokenBalance += amount;
}
/// @dev Deposit `amount` of base liquidity token from lending contract to this
function _depositToAaveFromBaseBalance(uint256 amount) private {
require(amount != 0, "amount cannot be 0");
require(amount <= baseTokenBalance, "amount exceeds base token balance!");
baseTokenBalance -= amount;
TransferHelper.safeApprove(address(baseLiquidityToken), address(unusedFundsLendingContract), amount);
unusedFundsLendingContract.deposit(address(baseLiquidityToken), amount, address(this), 0);
}
/// @dev Check pool balance, withdraw `amount` of base liquidity token from lending contract to this when `amount` > `baseTokenBalance`
function _ensureBaseBalance(uint256 amount) private {
require(amount != 0, "amount cannot be 0");
require(getPoolTotalLiquidAssetsValue() >= amount, "amount cannot be greater than total liquid asset value");
if (amount > baseTokenBalance) {
uint256 balanceDifference = amount - baseTokenBalance;
_withdrawFromAaveToBaseBalance(balanceDifference);
}
require(amount <= baseTokenBalance, "error ensuring base balance");
}
/// @dev Deposit base liquidity token from lending contract to this when `baseTokenBalance` >= `UNUSED_FUNDS_MIN_DEPOSIT_SIZE`
function _processMigrateUnusedFundsToLendingPool() private {
require(UNUSED_FUNDS_MIN_DEPOSIT_SIZE > 0, "UNUSED_FUNDS_MIN_DEPOSIT_SIZE > 0");
if (baseTokenBalance >= UNUSED_FUNDS_MIN_DEPOSIT_SIZE) {
_depositToAaveFromBaseBalance(baseTokenBalance);
}
}
/// @dev Mint `mintAmount` pool tokens for address `user`
function _mintPoolTokensForUser(address user, uint256 mintAmount) private {
require(user != address(0) && user != address(this), "invalid user");
require(mintAmount != 0, "mint amount cannot be 0");
uint256 newMintTokensCirculating = poolTokensCirculating + mintAmount;
poolTokensCirculating = newMintTokensCirculating;
poolLiquidityToken.mint(user, mintAmount);
require(poolTokensCirculating == newMintTokensCirculating);
}
/// @dev Handle donate
function _processDonation(address sender, uint256 depositAmount) private {
require(sender != address(0) && sender != address(this), "invalid sender");
require(depositAmount != 0, "depositAmount cannot be 0");
require(poolTokensCirculating != 0, "poolTokensCirculating must not be 0");
TransferHelper.safeTransferFrom(address(baseLiquidityToken), sender, address(this), depositAmount);
baseTokenBalance += depositAmount;
totalDonatedAllTime += depositAmount;
_processMigrateUnusedFundsToLendingPool();
emit Donation(sender, depositAmount);
}
/// @dev Called when `poolTokensCirculating` is 0
/// @return poolTokensOut
function _setupLiquidityFirst(address user, uint256 depositAmount) private returns (uint256) {
require(user != address(0) && user != address(this), "invalid user");
require(depositAmount != 0, "depositAmount cannot be 0");
require(poolTokensCirculating == 0, "poolTokensCirculating must be 0");
uint256 totalAssetValue = getPoolTotalAssetsValue();
TransferHelper.safeTransferFrom(address(baseLiquidityToken), user, address(this), depositAmount);
require(poolTokensCirculating == 0, "poolTokensCirculating must be 0");
require(getPoolTotalAssetsValue() == totalAssetValue, "total asset value must not change");
baseTokenBalance += depositAmount;
uint256 newTotalAssetValue = getPoolTotalAssetsValue();
require(newTotalAssetValue != 0 && newTotalAssetValue >= depositAmount);
uint256 poolTokensOut = newTotalAssetValue;
_mintPoolTokensForUser(user, poolTokensOut);
emit LiquidityAdded(user, depositAmount, poolTokensOut);
_processMigrateUnusedFundsToLendingPool();
return poolTokensOut;
}
/// @dev Called when `poolTokensCirculating` > 0
/// @return poolTokensOut
function _addLiquidityNormal(address user, uint256 depositAmount) private returns (uint256) {
require(user != address(0) && user != address(this), "invalid user");
require(depositAmount != 0, "depositAmount cannot be 0");
require(poolTokensCirculating != 0, "poolTokensCirculating must not be 0");
TransferHelper.safeTransferFrom(address(baseLiquidityToken), user, address(this), depositAmount);
require(poolTokensCirculating != 0, "poolTokensCirculating cannot be 0");
uint256 totalAssetValue = getPoolTotalAssetsValue();
require(totalAssetValue != 0, "total asset value cannot be 0");
uint256 poolTokensOut = getPoolDepositConversion(depositAmount);
baseTokenBalance += depositAmount;
_mintPoolTokensForUser(user, poolTokensOut);
emit LiquidityAdded(user, depositAmount, poolTokensOut);
_processMigrateUnusedFundsToLendingPool();
return poolTokensOut;
}
/// @dev Handle add liquidity
/// @return poolTokensOut
function _addLiquidity(address user, uint256 depositAmount) private returns (uint256) {
require(user != address(0) && user != address(this), "invalid user");
require(!nodeStakingPool.isNodeDecomissioning(), "BankNode bonded amount is less than 75% of the minimum");
require(depositAmount != 0, "depositAmount cannot be 0");
if (poolTokensCirculating == 0) {
return _setupLiquidityFirst(user, depositAmount);
} else {
return _addLiquidityNormal(user, depositAmount);
}
}
/// @dev Handle remove liquidity
/// @return baseTokensOut
function _removeLiquidity(address user, uint256 poolTokensToConsume) private returns (uint256) {
require(user != address(0) && user != address(this), "invalid user");
require(
poolTokensToConsume != 0 && poolTokensToConsume <= poolTokensCirculating,
"poolTokenAmount cannot be 0 or more than circulating"
);
require(poolTokensCirculating != 0, "poolTokensCirculating must not be 0");
require(getPoolTotalAssetsValue() != 0, "total asset value must not be 0");
uint256 baseTokensOut = getPoolWithdrawConversion(poolTokensToConsume);
poolTokensCirculating -= poolTokensToConsume;
_ensureBaseBalance(baseTokensOut);
require(baseTokenBalance >= baseTokensOut, "base tokens balance must be >= out");
TransferHelper.safeTransferFrom(address(poolLiquidityToken), user, address(this), poolTokensToConsume);
baseTokenBalance -= baseTokensOut;
TransferHelper.safeTransfer(address(baseLiquidityToken), user, baseTokensOut);
emit LiquidityRemoved(user, baseTokensOut, poolTokensToConsume);
return baseTokensOut;
}
/// @notice Donate `depositAmount` liquidity tokens to bankNode
/// @param depositAmount Amount of user deposit to liquidity pool
function donate(uint256 depositAmount) external override nonReentrant {
require(depositAmount != 0, "depositAmount cannot be 0");
_processDonation(msg.sender, depositAmount);
}
/// @notice Allow users to add liquidity tokens to liquidity pools.
/// @dev The user will be issued an equal number of pool tokens
///
/// @param depositAmount Amount of user deposit to liquidity pool
function addLiquidity(uint256 depositAmount) external override nonReentrant {
require(depositAmount != 0, "depositAmount cannot be 0");
require(
bnplKYCStore.checkUserBasicBitwiseMode(kycDomainId, msg.sender, LENDER_NEEDS_KYC) == 1,
"lender needs kyc"
);
_addLiquidity(msg.sender, depositAmount);
}
/// @notice Allow users to remove liquidity tokens from liquidity pools.
/// @dev Users need to replace liquidity tokens with the same amount of pool tokens
///
/// @param poolTokensToConsume Amount of user removes from the liquidity pool
function removeLiquidity(uint256 poolTokensToConsume) external override nonReentrant {
_removeLiquidity(msg.sender, poolTokensToConsume);
}
/// @dev Handle request loan
function _requestLoan(
address borrower,
uint256 loanAmount,
uint64 totalLoanDuration,
uint32 numberOfPayments,
uint256 interestRatePerPayment,
uint8 messageType,
string memory message,
string memory uuid
) private {
require(loanAmount <= MAX_LOAN_AMOUNT && loanAmount >= MIN_LOAN_AMOUNT && interestRatePerPayment > 0);
uint256 amountPerPayment = BankNodeUtils.getMonthlyPayment(
loanAmount,
interestRatePerPayment,
numberOfPayments
);
require(loanAmount <= (amountPerPayment * uint256(numberOfPayments)), "payments not greater than loan amount!");
require(
((totalLoanDuration / uint256(numberOfPayments)) * uint256(numberOfPayments)) == totalLoanDuration,
"totalLoanDuration must be a multiple of numberOfPayments"
);
require(totalLoanDuration >= MIN_LOAN_DURATION, "must be greater than MIN_LOAN_DURATION");
require(totalLoanDuration <= MAX_LOAN_DURATION, "must be lower than MAX_LOAN_DURATION");
require(
(uint256(totalLoanDuration) / uint256(numberOfPayments)) >= MIN_LOAN_PAYMENT_INTERVAL,
"must be greater than MIN_LOAN_PAYMENT_INTERVAL"
);
require(
(uint256(totalLoanDuration) / uint256(numberOfPayments)) <= MAX_LOAN_PAYMENT_INTERVAL,
"must be lower than MAX_LOAN_PAYMENT_INTERVAL"
);
uint256 currentLoanRequestId = loanRequestIndex;
loanRequestIndex += 1;
LoanRequest storage loanRequest = loanRequests[currentLoanRequestId];
require(loanRequest.borrower == address(0));
loanRequest.borrower = borrower;
loanRequest.loanAmount = loanAmount;
loanRequest.totalLoanDuration = totalLoanDuration;
loanRequest.interestRatePerPayment = interestRatePerPayment;
loanRequest.numberOfPayments = numberOfPayments;
loanRequest.amountPerPayment = amountPerPayment;
loanRequest.status = 0;
loanRequest.messageType = messageType;
loanRequest.message = message;
loanRequest.uuid = uuid;
emit LoanRequested(borrower, loanAmount, currentLoanRequestId, uuid);
}
/// @notice Allows users to request a loan from the bank node
///
/// @param loanAmount The loan amount
/// @param totalLoanDuration The total loan duration (secs)
/// @param numberOfPayments The number of payments
/// @param interestRatePerPayment The interest rate per payment
/// @param messageType 0 = plain text, 1 = encrypted with the public key
/// @param message Writing detailed messages may increase loan approval rates
/// @param uuid The `LoanRequested` event contains this uuid for easy identification
function requestLoan(
uint256 loanAmount,
uint64 totalLoanDuration,
uint32 numberOfPayments,
uint256 interestRatePerPayment,
uint8 messageType,
string memory message,
string memory uuid
) external override nonReentrant {
require(
bnplKYCStore.checkUserBasicBitwiseMode(kycDomainId, msg.sender, BORROWER_NEEDS_KYC) == 1,
"borrower needs kyc"
);
_requestLoan(
msg.sender,
loanAmount,
totalLoanDuration,
numberOfPayments,
interestRatePerPayment,
messageType,
message,
uuid
);
}
/// @dev Handle approve loan request
function _approveLoanRequest(address operator, uint256 loanRequestId) private {
require(loanRequestId < loanRequestIndex, "loan request must exist");
LoanRequest storage loanRequest = loanRequests[loanRequestId];
require(loanRequest.borrower != address(0));
require(loanRequest.status == 0, "loan must not already be approved/rejected");
require(!nodeStakingPool.isNodeDecomissioning(), "BankNode bonded amount is less than 75% of the minimum");
uint256 loanAmount = loanRequest.loanAmount;
require(
loanAmount <= (loanRequest.amountPerPayment * uint256(loanRequest.numberOfPayments)),
"payments not greater than loan amount!"
);
require(
((loanRequest.totalLoanDuration / uint256(loanRequest.numberOfPayments)) *
uint256(loanRequest.numberOfPayments)) == loanRequest.totalLoanDuration,
"totalLoanDuration must be a multiple of numberOfPayments"
);
require(loanRequest.totalLoanDuration >= MIN_LOAN_DURATION, "must be greater than MIN_LOAN_DURATION");
require(loanRequest.totalLoanDuration <= MAX_LOAN_DURATION, "must be lower than MAX_LOAN_DURATION");
require(
(uint256(loanRequest.totalLoanDuration) / uint256(loanRequest.numberOfPayments)) >=
MIN_LOAN_PAYMENT_INTERVAL,
"must be greater than MIN_LOAN_PAYMENT_INTERVAL"
);
require(
(uint256(loanRequest.totalLoanDuration) / uint256(loanRequest.numberOfPayments)) <=
MAX_LOAN_PAYMENT_INTERVAL,
"must be lower than MAX_LOAN_PAYMENT_INTERVAL"
);
uint256 currentLoanId = loanIndex;
loanIndex += 1;
loanRequest.status = 4;
loanRequest.loanId = currentLoanId;
loanRequest.statusUpdatedAt = uint64(block.timestamp);
loanRequest.statusModifiedBy = operator;
Loan storage loan = loans[currentLoanId];
require(loan.borrower == address(0));
loan.borrower = loanRequest.borrower;
loan.loanAmount = loanAmount;
loan.totalLoanDuration = loanRequest.totalLoanDuration;
loan.numberOfPayments = loanRequest.numberOfPayments;
loan.amountPerPayment = loanRequest.amountPerPayment;
loan.interestRatePerPayment = loanRequest.interestRatePerPayment;
loan.loanStartedAt = uint64(block.timestamp);
loan.numberOfPaymentsMade = 0;
loan.remainingBalance = uint256(loan.numberOfPayments) * uint256(loan.amountPerPayment);
loan.status = 0;
loan.loanRequestId = loanRequestId;
onGoingLoanCount++;
totalAmountOfLoans += loanAmount;
totalAmountOfActiveLoans += loanAmount;
_ensureBaseBalance(loanAmount);
baseTokenBalance -= loanAmount;
accountsReceivableFromLoans += loanAmount;
TransferHelper.safeTransfer(address(baseLiquidityToken), loan.borrower, loanAmount);
emit LoanApproved(loan.borrower, loanRequestId, currentLoanId, loanAmount, operator);
}
/// @dev Handle deny loan request
function _denyLoanRequest(address operator, uint256 loanRequestId) private {
require(loanRequestId < loanRequestIndex, "loan request must exist");
LoanRequest storage loanRequest = loanRequests[loanRequestId];
require(loanRequest.borrower != address(0));
require(loanRequest.status == 0, "loan must not already be approved/rejected");
loanRequest.status = 1;
loanRequest.statusUpdatedAt = uint64(block.timestamp);
loanRequest.statusModifiedBy = operator;
emit LoanDenied(loanRequest.borrower, loanRequestId, operator);
}
/// @notice Deny a loan request with id `loanRequestId`
///
/// - PRIVILEGES REQUIRED:
/// Admins with the role "OPERATOR_ROLE"
///
/// @param loanRequestId The id of loan request
function denyLoanRequest(uint256 loanRequestId) external override nonReentrant onlyRole(OPERATOR_ROLE) {
_denyLoanRequest(msg.sender, loanRequestId);
}
/// @notice Approve a loan request with id `loanRequestId`
/// - This also sends the lending token requested to the borrower
///
/// - PRIVILEGES REQUIRED:
/// Admins with the role "OPERATOR_ROLE"
///
/// @param loanRequestId The id of loan request
function approveLoanRequest(uint256 loanRequestId) external override nonReentrant onlyRole(OPERATOR_ROLE) {
_approveLoanRequest(msg.sender, loanRequestId);
}
/// @notice Change kyc settings of bank node
/// - Including `setKYCDomainMode` and `setKYCDomainPublicKey`
///
/// - PRIVILEGES REQUIRED:
/// Admins with the role "OPERATOR_ROLE"
///
/// @param kycMode_ KYC mode
/// @param nodePublicKey_ Bank node KYC public key
function setKYCSettings(uint256 kycMode_, address nodePublicKey_)
external
override
nonReentrant
onlyRole(OPERATOR_ROLE)
{
bnplKYCStore.setKYCDomainMode(kycDomainId, kycMode_);
bnplKYCStore.setKYCDomainPublicKey(kycDomainId, nodePublicKey_);
}
/// @notice Set KYC mode for specified kycdomain
///
/// - PRIVILEGES REQUIRED:
/// Admins with the role "OPERATOR_ROLE"
///
/// @param domain KYC domain
/// @param mode KYC mode
function setKYCDomainMode(uint32 domain, uint256 mode) external override nonReentrant onlyRole(OPERATOR_ROLE) {
bnplKYCStore.setKYCDomainMode(domain, mode);
}
/// @notice Withdraw `amount` of balance to an address
///
/// - PRIVILEGES REQUIRED:
/// Admins with the role "OPERATOR_ROLE"
///
/// @param amount Withdraw amount
/// @param to Receiving address
function withdrawNodeOperatorBalance(uint256 amount, address to)
external
override
nonReentrant
onlyRole(OPERATOR_ROLE)
{
require(nodeOperatorBalance >= amount, "cannot withdraw more than nodeOperatorBalance");
_ensureBaseBalance(amount);
nodeOperatorBalance -= amount;
TransferHelper.safeTransfer(address(baseLiquidityToken), to, amount);
}
/// @dev Swap liquidity token to BNP for staking pool
function _marketBuyBNPLForStakingPool(uint256 amountInBaseToken, uint256 minTokenOut) private {
require(amountInBaseToken > 0);
TransferHelper.safeApprove(address(baseLiquidityToken), address(bnplSwapMarket), amountInBaseToken);
uint256 amountOut = bnplSwapMarket.swapExactTokensForTokens(
amountInBaseToken,
minTokenOut,
BankNodeUtils.getSwapExactTokensPath(address(baseLiquidityToken), address(bnplToken)),
address(this),
block.timestamp
)[2];
require(amountOut >= minTokenOut, "swap amount must >= minTokenOut");
TransferHelper.safeApprove(address(bnplToken), address(nodeStakingPool), amountOut);
nodeStakingPool.donateNotCountedInTotal(amountOut);
}
/// @dev Swap BNPL to liquidity token for slashing
function _marketSellBNPLForSlashing(uint256 bnplAmount, uint256 minTokenOut) private {
require(bnplAmount > 0);
TransferHelper.safeApprove(address(bnplToken), address(bnplSwapMarket), bnplAmount);
uint256 amountOut = bnplSwapMarket.swapExactTokensForTokens(
bnplAmount,
minTokenOut,
BankNodeUtils.getSwapExactTokensPath(address(bnplToken), address(baseLiquidityToken)),
address(this),
block.timestamp
)[2];
require(amountOut >= minTokenOut, "swap amount must >= minTokenOut");
baseTokenBalance += amountOut;
}
/// @dev Handle report overdue loan
function _markLoanAsWriteOff(uint256 loanId, uint256 minTokenOut) private {
Loan storage loan = loans[loanId];
require(loan.borrower != address(0));
require(
loan.loanStartedAt < uint64(block.timestamp),
"cannot make the loan payment on same block loan is created"
);
require(loan.remainingBalance > 0, "loan must not be paid off");
require(loan.status == 0 || loan.status != 2, "loan must not be paid off or already overdue");
require(
getLoanNextDueDate(loanId) < uint64(block.timestamp - bankNodeManager.loanOverdueGracePeriod()),
"loan must be overdue"
);
require(loan.loanAmount > loan.totalAmountPaid);
uint256 startPoolTotalAssetValue = getPoolTotalAssetsValue();
loan.status = 2;
onGoingLoanCount--;
totalAmountOfActiveLoans -= loan.loanAmount;
if (loan.totalAmountPaid >= loan.loanAmount) {
netEarnings = netEarnings + loan.totalAmountPaid - loan.loanAmount;
}
//loan.loanAmount-principalPaidForLoan[loanId]
//uint256 total3rdPartyInterestPaid = loanBondedAmount[loanId]; // bnpl market buy is the same amount as the amount bonded, this must change if they are not equal
uint256 interestRecirculated = (interestPaidForLoan[loanId] * 7) / 10; // 10% paid to market buy bnpl, 10% bonded
uint256 accountsReceivableLoss = loan.loanAmount - (loan.totalAmountPaid - interestPaidForLoan[loanId]);
accountsReceivableFromLoans -= accountsReceivableLoss;
uint256 prevBalanceEquivalent = startPoolTotalAssetValue - interestRecirculated;
totalLossAllTime += prevBalanceEquivalent - getPoolTotalAssetsValue();
totalLoansDefaulted += 1;
require(prevBalanceEquivalent > getPoolTotalAssetsValue());
uint256 poolBalance = nodeStakingPool.getPoolTotalAssetsValue();
require(poolBalance > 0);
uint256 slashAmount = BankNodeUtils.calculateSlashAmount(
prevBalanceEquivalent,
prevBalanceEquivalent - getPoolTotalAssetsValue(),
poolBalance
);
require(slashAmount > 0);
nodeStakingPool.slash(slashAmount);
_marketSellBNPLForSlashing(slashAmount, minTokenOut);
//uint256 lossAmount = accountsReceivableLoss+amountPaidToBNPLMarketBuy;
}
/// @notice Allows users report a loan with id `loanId` as being overdue
/// - This method will call the swap contract, so `minTokenOut` is required
///
/// @param loanId The id of loan
/// @param minTokenOut The minimum output token of swap, if the swap result is less than this value, it will fail
function reportOverdueLoan(uint256 loanId, uint256 minTokenOut) external override nonReentrant {
_markLoanAsWriteOff(loanId, minTokenOut);
}
/// @dev Handle make loan payment
function _makeLoanPayment(
address payer,
uint256 loanId,
uint256 minTokenOut
) private {
require(loanId < loanIndex, "loan request must exist");
Loan storage loan = loans[loanId];
require(loan.borrower != address(0));
require(
loan.loanStartedAt < uint64(block.timestamp),
"cannot make the loan payment on same block loan is created"
);
require(
uint64(block.timestamp - bankNodeManager.loanOverdueGracePeriod()) <= getLoanNextDueDate(loanId),
"loan is overdue and exceeding the grace period"
);
uint256 currentPaymentId = loan.numberOfPaymentsMade;
require(
currentPaymentId < loan.numberOfPayments &&
loan.remainingBalance > 0 &&
loan.remainingBalance >= loan.amountPerPayment
);
uint256 interestAmount = BankNodeUtils.getMonthlyInterestPayment(
loan.loanAmount,
loan.interestRatePerPayment,
loan.numberOfPayments,
loan.numberOfPaymentsMade + 1
);
uint256 holdInterest = (interestAmount * 3) / 10;
//uint returnInterest = interestAmount - holdInterest;
uint256 bondedInterest = holdInterest / 3;
uint256 marketBuyInterest = holdInterest - bondedInterest;
uint256 amountPerPayment = loan.amountPerPayment;
require(interestAmount > 0 && bondedInterest > 0 && marketBuyInterest > 0 && amountPerPayment > interestAmount);
TransferHelper.safeTransferFrom(address(baseLiquidityToken), payer, address(this), amountPerPayment);
loan.totalAmountPaid += amountPerPayment;
loan.remainingBalance -= amountPerPayment;
// rounding errors can sometimes cause this to integer overflow, so we add a Math.min around the accountsReceivableFromLoans update
accountsReceivableFromLoans -= BankNodeUtils.min(
amountPerPayment - interestAmount,
accountsReceivableFromLoans
);
interestPaidForLoan[loanId] += interestAmount;
loan.numberOfPaymentsMade = loan.numberOfPaymentsMade + 1;
nodeOperatorBalance += bondedInterest;
baseTokenBalance += amountPerPayment - holdInterest;
_marketBuyBNPLForStakingPool(marketBuyInterest, minTokenOut);
if (loan.remainingBalance == 0) {
loan.status = 1;
loan.statusUpdatedAt = uint64(block.timestamp);
onGoingLoanCount--;
totalAmountOfActiveLoans -= loan.loanAmount;
if (loan.totalAmountPaid >= loan.loanAmount) {
netEarnings = netEarnings + loan.totalAmountPaid - loan.loanAmount;
}
}
_processMigrateUnusedFundsToLendingPool();
emit LoanPayment(loan.borrower, loanId, amountPerPayment);
}
/// @notice Make a loan payment for loan with id `loanId`
/// - This method will call the swap contract, so `minTokenOut` is required
///
/// @param loanId The id of loan
/// @param minTokenOut The minimum output token of swap, if the swap result is less than this value, it will fail
function makeLoanPayment(uint256 loanId, uint256 minTokenOut) external override nonReentrant {
_makeLoanPayment(msg.sender, loanId, minTokenOut);
}
/// @dev Returns `unusedFundsLendingToken` as array
function _dividendAssets() internal view returns (address[] memory) {
address[] memory assets = new address[](1);
assets[0] = address(unusedFundsLendingToken);
return assets;
}
/// @notice Get reward token (stkAAVE) unclaimed rewards balance of bank node
/// @return rewardsBalance
function getRewardsBalance() external view override returns (uint256) {
return unusedFundsIncentivesController.getRewardsBalance(_dividendAssets(), address(this));
}
/// @notice Get reward token (stkAAVE) cool down start time of staking pool
/// @return cooldownStartTimestamp
function getCooldownStartTimestamp() external view override returns (uint256) {
return rewardToken().stakersCooldowns(address(nodeStakingPool));
}
/// @notice Get reward token (stkAAVE) rewards balance of staking pool
/// @return stakedTokenRewardsBalance
function getStakedTokenRewardsBalance() external view override returns (uint256) {
return rewardToken().getTotalRewardsBalance(address(nodeStakingPool));
}
/// @notice Get reward token (stkAAVE) balance of staking pool
/// @return stakedTokenBalance
function getStakedTokenBalance() external view override returns (uint256) {
return IERC20(address(rewardToken())).balanceOf(address(nodeStakingPool));
}
/// @notice Claim lending token interest
///
/// - PRIVILEGES REQUIRED:
/// Admins with the role "OPERATOR_ROLE"
///
/// @return lendingTokenInterest
function claimLendingTokenInterest() external override onlyRole(OPERATOR_ROLE) nonReentrant returns (uint256) {
TransferHelper.safeApprove(
rewardToken().REWARD_TOKEN(),
address(unusedFundsIncentivesController),
type(uint256).max
);
return
unusedFundsIncentivesController.claimRewards(
_dividendAssets(),
type(uint256).max,
address(nodeStakingPool)
);
}
}
|
Allow users to remove liquidity tokens from liquidity pools. Users need to replace liquidity tokens with the same amount of pool tokens poolTokensToConsume Amount of user removes from the liquidity pool
|
function removeLiquidity(uint256 poolTokensToConsume) external override nonReentrant {
_removeLiquidity(msg.sender, poolTokensToConsume);
}
| 6,397,073 |
/**
* Submitted for verification at Etherscan.io on 2022-03-24
*/
// _/_/ _/ _/ _/ _/_/_/ _/_/ _/_/
// _/ _/ _/_/_/ _/_/_/_/ _/_/_/ _/ _/_/ _/ _/ _/ _/ _/ _/ _/
// _/ _/_/ _/ _/ _/ _/ _/ _/_/ _/ _/ _/ _/ _/ _/
// _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/
// _/_/ _/ _/_/_/ _/_/ _/_/_/ _/ _/ _/ _/_/_/ _/_/_/_/ _/_/_/_/
/*
* Website
* http://qatarwc.xyz
*
* Telegram
* https://t.me/fifaqatarwc22
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
contract QaTarWC is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public constant uniswapV2Router =
IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uint256 public buyLiquidityFee = 2;
uint256 public sellLiquidityFee = 3;
uint256 public buyTxFee = 8;
uint256 public sellTxFee = 10;
uint256 public tokensForLiquidity;
uint256 public tokensForTax;
uint256 public _tTotal = 10**18; // 1 billion according to 9 decimals
uint256 public swapAtAmount;
uint256 public maxTxLimit;
uint256 public maxWalletLimit;
address public dev;
address public immutable deployer;
address public uniswapV2Pair;
uint256 private launchBlock;
bool private isSwapping;
bool public isLaunched;
// exclude from fees
mapping(address => bool) public isExcludedFromFees;
// exclude from max transaction amount
mapping(address => bool) public isExcludedFromTxLimit;
// exclude from max wallet limit
mapping(address => bool) public isExcludedFromWalletLimit;
// if the account is blacklisted from trading
mapping(address => bool) public isBlacklisted;
constructor(address _dev) ERC20("QaTarWC", "QWC") {
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(
address(this),
uniswapV2Router.WETH()
);
_approve(address(this), address(uniswapV2Router), type(uint256).max);
// exclude from fees, wallet limit and transaction limit
excludeFromAllLimits(owner(), true);
excludeFromAllLimits(address(this), true);
excludeFromWalletLimit(uniswapV2Pair, true);
excludeFromAllLimits(0x000000000000000000000000000000000000dEaD, true);
dev = _dev;
deployer = _msgSender();
swapAtAmount = _tTotal.mul(10).div(10000); // 0.10% of total supply
maxTxLimit = _tTotal.mul(80).div(10000); // 0.80% of total supply
maxWalletLimit = _tTotal.mul(160).div(10000); // 1.60% of total supply
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(owner(), _tTotal);
}
function decimals() public pure override(ERC20) returns (uint8) {
return 9;
}
function excludeFromFees(address account, bool value) public onlyOwner {
require(
isExcludedFromFees[account] != value,
"Fees: Already set to this value"
);
isExcludedFromFees[account] = value;
}
function excludeFromTxLimit(address account, bool value) public onlyOwner {
require(
isExcludedFromTxLimit[account] != value,
"TxLimit: Already set to this value"
);
isExcludedFromTxLimit[account] = value;
}
function excludeFromWalletLimit(address account, bool value)
public
onlyOwner
{
require(
isExcludedFromWalletLimit[account] != value,
"WalletLimit: Already set to this value"
);
isExcludedFromWalletLimit[account] = value;
}
function excludeFromAllLimits(address account, bool value)
public
onlyOwner
{
excludeFromFees(account, value);
excludeFromTxLimit(account, value);
excludeFromWalletLimit(account, value);
}
function setBuyFee(uint256 liquidityFee, uint256 txFee) external onlyOwner {
buyLiquidityFee = liquidityFee;
buyTxFee = txFee;
}
function setSellFee(uint256 liquidityFee, uint256 txFee)
external
onlyOwner
{
sellLiquidityFee = liquidityFee;
sellTxFee = txFee;
}
function setMaxTxLimit(uint256 newLimit) external onlyOwner {
maxTxLimit = newLimit * (10**9);
}
function setMaxWalletLimit(uint256 newLimit) external onlyOwner {
maxWalletLimit = newLimit * (10**9);
}
function setSwapAtAmount(uint256 amountToSwap) external onlyOwner {
swapAtAmount = amountToSwap * (10**9);
}
function updateDevWallet(address newWallet) external onlyOwner {
dev = newWallet;
}
function addBlacklist(address account) external onlyOwner {
require(!isBlacklisted[account], "Blacklist: Already blacklisted");
require(account != uniswapV2Pair, "Cannot blacklist pair");
_setBlacklist(account, true);
}
function removeBlacklist(address account) external onlyOwner {
require(isBlacklisted[account], "Blacklist: Not blacklisted");
_setBlacklist(account, false);
}
function launchNow() external onlyOwner {
require(!isLaunched, "Contract is already launched");
isLaunched = true;
launchBlock = block.number;
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "transfer from the zero address");
require(to != address(0), "transfer to the zero address");
require(
amount <= maxTxLimit ||
isExcludedFromTxLimit[from] ||
isExcludedFromTxLimit[to],
"Tx Amount too large"
);
require(
balanceOf(to).add(amount) <= maxWalletLimit ||
isExcludedFromWalletLimit[to],
"Transfer will exceed wallet limit"
);
require(
isLaunched || isExcludedFromFees[from] || isExcludedFromFees[to],
"Waiting to go live"
);
require(!isBlacklisted[from], "Sender is blacklisted");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
uint256 totalTokensForFee = tokensForLiquidity + tokensForTax;
bool canSwap = totalTokensForFee >= swapAtAmount;
if (from != uniswapV2Pair && canSwap && !isSwapping) {
isSwapping = true;
swapBack(totalTokensForFee);
isSwapping = false;
} else if (
from == uniswapV2Pair &&
to != uniswapV2Pair &&
block.number < launchBlock + 2 &&
!isExcludedFromFees[to]
) {
_setBlacklist(to, true);
}
bool takeFee = !isSwapping;
if (isExcludedFromFees[from] || isExcludedFromFees[to]) {
takeFee = false;
}
if (takeFee) {
uint256 fees;
// on sell
if (to == uniswapV2Pair) {
uint256 sellTotalFees = sellLiquidityFee.add(sellTxFee);
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity = tokensForLiquidity.add(
fees.mul(sellLiquidityFee).div(sellTotalFees)
);
tokensForTax = tokensForTax.add(
fees.mul(sellTxFee).div(sellTotalFees)
);
}
// on buy & wallet transfers
else {
uint256 buyTotalFees = buyLiquidityFee.add(buyTxFee);
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity = tokensForLiquidity.add(
fees.mul(buyLiquidityFee).div(buyTotalFees)
);
tokensForTax = tokensForTax.add(
fees.mul(buyTxFee).div(buyTotalFees)
);
}
if (fees > 0) {
super._transfer(from, address(this), fees);
amount = amount.sub(fees);
}
}
super._transfer(from, to, amount);
}
function swapBack(uint256 totalTokensForFee) private {
uint256 toSwap = swapAtAmount;
// Halve the amount of liquidity tokens
uint256 liquidityTokens = toSwap
.mul(tokensForLiquidity)
.div(totalTokensForFee)
.div(2);
uint256 taxTokens = toSwap.sub(liquidityTokens).sub(liquidityTokens);
uint256 amountToSwapForETH = toSwap.sub(liquidityTokens);
_swapTokensForETH(amountToSwapForETH);
uint256 ethBalance = address(this).balance;
uint256 ethForTax = ethBalance.mul(taxTokens).div(amountToSwapForETH);
uint256 ethForLiquidity = ethBalance.sub(ethForTax);
tokensForLiquidity = tokensForLiquidity.sub(liquidityTokens.mul(2));
tokensForTax = tokensForTax.sub(toSwap.sub(liquidityTokens.mul(2)));
payable(address(dev)).transfer(ethForTax);
_addLiquidity(liquidityTokens, ethForLiquidity);
}
function _addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0,
0,
deployer,
block.timestamp
);
}
function _swapTokensForETH(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function _setBlacklist(address account, bool value) internal {
isBlacklisted[account] = value;
}
receive() external payable {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
|
on sell on buy & wallet transfers
|
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "transfer from the zero address");
require(to != address(0), "transfer to the zero address");
require(
amount <= maxTxLimit ||
isExcludedFromTxLimit[from] ||
isExcludedFromTxLimit[to],
"Tx Amount too large"
);
require(
balanceOf(to).add(amount) <= maxWalletLimit ||
isExcludedFromWalletLimit[to],
"Transfer will exceed wallet limit"
);
require(
isLaunched || isExcludedFromFees[from] || isExcludedFromFees[to],
"Waiting to go live"
);
require(!isBlacklisted[from], "Sender is blacklisted");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
uint256 totalTokensForFee = tokensForLiquidity + tokensForTax;
bool canSwap = totalTokensForFee >= swapAtAmount;
if (from != uniswapV2Pair && canSwap && !isSwapping) {
isSwapping = true;
swapBack(totalTokensForFee);
isSwapping = false;
} else if (
from == uniswapV2Pair &&
to != uniswapV2Pair &&
block.number < launchBlock + 2 &&
!isExcludedFromFees[to]
) {
_setBlacklist(to, true);
}
bool takeFee = !isSwapping;
if (isExcludedFromFees[from] || isExcludedFromFees[to]) {
takeFee = false;
}
if (takeFee) {
uint256 fees;
if (to == uniswapV2Pair) {
uint256 sellTotalFees = sellLiquidityFee.add(sellTxFee);
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity = tokensForLiquidity.add(
fees.mul(sellLiquidityFee).div(sellTotalFees)
);
tokensForTax = tokensForTax.add(
fees.mul(sellTxFee).div(sellTotalFees)
);
}
else {
uint256 buyTotalFees = buyLiquidityFee.add(buyTxFee);
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity = tokensForLiquidity.add(
fees.mul(buyLiquidityFee).div(buyTotalFees)
);
tokensForTax = tokensForTax.add(
fees.mul(buyTxFee).div(buyTotalFees)
);
}
if (fees > 0) {
super._transfer(from, address(this), fees);
amount = amount.sub(fees);
}
}
super._transfer(from, to, amount);
}
| 10,266,798 |
pragma solidity 0.5.11;
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract Governable {
// Storage position of the owner and pendingOwner of the contract
bytes32
private constant governorPosition = 0x7bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a;
//keccak256("OUSD.governor");
bytes32
private constant pendingGovernorPosition = 0x44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db;
//keccak256("OUSD.pending.governor");
event PendingGovernorshipTransfer(
address indexed previousGovernor,
address indexed newGovernor
);
event GovernorshipTransferred(
address indexed previousGovernor,
address indexed newGovernor
);
/**
* @dev Initializes the contract setting the deployer as the initial Governor.
*/
constructor() internal {
_setGovernor(msg.sender);
emit GovernorshipTransferred(address(0), _governor());
}
/**
* @dev Returns the address of the current Governor.
*/
function governor() public view returns (address) {
return _governor();
}
function _governor() internal view returns (address governorOut) {
bytes32 position = governorPosition;
assembly {
governorOut := sload(position)
}
}
function _pendingGovernor()
internal
view
returns (address pendingGovernor)
{
bytes32 position = pendingGovernorPosition;
assembly {
pendingGovernor := sload(position)
}
}
/**
* @dev Throws if called by any account other than the Governor.
*/
modifier onlyGovernor() {
require(isGovernor(), "Caller is not the Governor");
_;
}
/**
* @dev Returns true if the caller is the current Governor.
*/
function isGovernor() public view returns (bool) {
return msg.sender == _governor();
}
function _setGovernor(address newGovernor) internal {
bytes32 position = governorPosition;
assembly {
sstore(position, newGovernor)
}
}
function _setPendingGovernor(address newGovernor) internal {
bytes32 position = pendingGovernorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @dev Transfers Governance of the contract to a new account (`newGovernor`).
* Can only be called by the current Governor. Must be claimed for this to complete
* @param _newGovernor Address of the new Governor
*/
function transferGovernance(address _newGovernor) external onlyGovernor {
_setPendingGovernor(_newGovernor);
emit PendingGovernorshipTransfer(_governor(), _newGovernor);
}
/**
* @dev Claim Governance of the contract to a new account (`newGovernor`).
* Can only be called by the new Governor.
*/
function claimGovernance() external {
require(
msg.sender == _pendingGovernor(),
"Only the pending Governor can complete the claim"
);
_changeGovernor(msg.sender);
}
/**
* @dev Change Governance of the contract to a new account (`newGovernor`).
* @param _newGovernor Address of the new Governor
*/
function _changeGovernor(address _newGovernor) internal {
require(_newGovernor != address(0), "New Governor is address(0)");
emit GovernorshipTransferred(_governor(), _newGovernor);
_setGovernor(_newGovernor);
}
}
contract InitializableGovernable is Governable, Initializable {
function _initialize(address _governor) internal {
_changeGovernor(_governor);
}
}
interface IStrategy {
/**
* @dev Deposit the given asset to Lending platform.
* @param _asset asset address
* @param _amount Amount to deposit
*/
function deposit(address _asset, uint256 _amount)
external
returns (uint256 amountDeposited);
/**
* @dev Withdraw given asset from Lending platform
*/
function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external returns (uint256 amountWithdrawn);
/**
* @dev Returns the current balance of the given asset.
*/
function checkBalance(address _asset)
external
view
returns (uint256 balance);
/**
* @dev Returns bool indicating whether strategy supports asset.
*/
function supportsAsset(address _asset) external view returns (bool);
/**
* @dev Liquidate all assets in strategy and return them to Vault.
*/
function liquidate() external;
/**
* @dev Get the APR for the Strategy.
*/
function getAPR() external view returns (uint256);
/**
* @dev Collect reward tokens from the Strategy.
*/
function collectRewardToken() external;
}
interface ICERC20 {
/**
* @notice The mint function transfers an asset into the protocol, which begins accumulating
* interest based on the current Supply Rate for the asset. The user receives a quantity of
* cTokens equal to the underlying tokens supplied, divided by the current Exchange Rate.
* @param mintAmount The amount of the asset to be supplied, in units of the underlying asset.
* @return 0 on success, otherwise an Error codes
*/
function mint(uint256 mintAmount) external returns (uint256);
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise an error code.
*/
function redeem(uint256 redeemTokens) external returns (uint256);
/**
* @notice The redeem underlying function converts cTokens into a specified quantity of the underlying
* asset, and returns them to the user. The amount of cTokens redeemed is equal to the quantity of
* underlying tokens received, divided by the current Exchange Rate. The amount redeemed must be less
* than the user's Account Liquidity and the market's available liquidity.
* @param redeemAmount The amount of underlying to be redeemed.
* @return 0 on success, otherwise an error code.
*/
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
/**
* @notice The user's underlying balance, representing their assets in the protocol, is equal to
* the user's cToken balance multiplied by the Exchange Rate.
* @param owner The account to get the underlying balance of.
* @return The amount of underlying currently owned by the account.
*/
function balanceOfUnderlying(address owner) external returns (uint256);
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() external view returns (uint256);
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @notice Get the supply rate per block for supplying the token to Compound.
*/
function supplyRatePerBlock() external view returns (uint256);
}
contract InitializableAbstractStrategy is IStrategy, Initializable, Governable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
event PTokenAdded(address indexed _asset, address _pToken);
event Deposit(address indexed _asset, address _pToken, uint256 _amount);
event Withdrawal(address indexed _asset, address _pToken, uint256 _amount);
// Core address for the given platform
address public platformAddress;
address public vaultAddress;
// asset => pToken (Platform Specific Token Address)
mapping(address => address) public assetToPToken;
// Full list of all assets supported here
address[] internal assetsMapped;
// Reward token address
address public rewardTokenAddress;
/**
* @dev Internal initialize function, to set up initial internal state
* @param _platformAddress jGeneric platform address
* @param _vaultAddress Address of the Vault
* @param _rewardTokenAddress Address of reward token for platform
* @param _assets Addresses of initial supported assets
* @param _pTokens Platform Token corresponding addresses
*/
function initialize(
address _platformAddress,
address _vaultAddress,
address _rewardTokenAddress,
address[] calldata _assets,
address[] calldata _pTokens
) external onlyGovernor initializer {
InitializableAbstractStrategy._initialize(
_platformAddress,
_vaultAddress,
_rewardTokenAddress,
_assets,
_pTokens
);
}
function _initialize(
address _platformAddress,
address _vaultAddress,
address _rewardTokenAddress,
address[] memory _assets,
address[] memory _pTokens
) internal {
platformAddress = _platformAddress;
vaultAddress = _vaultAddress;
rewardTokenAddress = _rewardTokenAddress;
uint256 assetCount = _assets.length;
require(assetCount == _pTokens.length, "Invalid input arrays");
for (uint256 i = 0; i < assetCount; i++) {
_setPTokenAddress(_assets[i], _pTokens[i]);
}
}
/**
* @dev Verifies that the caller is the Vault.
*/
modifier onlyVault() {
require(msg.sender == vaultAddress, "Caller is not the Vault");
_;
}
/**
* @dev Verifies that the caller is the Vault or Governor.
*/
modifier onlyVaultOrGovernor() {
require(
msg.sender == vaultAddress || msg.sender == governor(),
"Caller is not the Vault or Governor"
);
_;
}
/**
* @dev Set the reward token address.
* @param _rewardTokenAddress Address of the reward token
*/
function setRewardTokenAddress(address _rewardTokenAddress)
external
onlyGovernor
{
rewardTokenAddress = _rewardTokenAddress;
}
/**
* @dev Provide support for asset by passing its pToken address.
* This method can only be called by the system Governor
* @param _asset Address for the asset
* @param _pToken Address for the corresponding platform token
*/
function setPTokenAddress(address _asset, address _pToken)
external
onlyGovernor
{
_setPTokenAddress(_asset, _pToken);
}
/**
* @dev Provide support for asset by passing its pToken address.
* Add to internal mappings and execute the platform specific,
* abstract method `_abstractSetPToken`
* @param _asset Address for the asset
* @param _pToken Address for the corresponding platform token
*/
function _setPTokenAddress(address _asset, address _pToken) internal {
require(assetToPToken[_asset] == address(0), "pToken already set");
require(
_asset != address(0) && _pToken != address(0),
"Invalid addresses"
);
assetToPToken[_asset] = _pToken;
assetsMapped.push(_asset);
emit PTokenAdded(_asset, _pToken);
_abstractSetPToken(_asset, _pToken);
}
/**
* @dev Transfer token to governor. Intended for recovering tokens stuck in
* strategy contracts, i.e. mistaken sends.
* @param _asset Address for the asset
* @param _amount Amount of the asset to transfer
*/
function transferToken(address _asset, uint256 _amount)
public
onlyGovernor
{
IERC20(_asset).transfer(governor(), _amount);
}
/***************************************
Abstract
****************************************/
function _abstractSetPToken(address _asset, address _pToken) internal;
function safeApproveAllTokens() external;
/**
* @dev Deposit a amount of asset into the platform
* @param _asset Address for the asset
* @param _amount Units of asset to deposit
* @return amountDeposited Quantity of asset that was deposited
*/
function deposit(address _asset, uint256 _amount)
external
returns (uint256 amountDeposited);
/**
* @dev Withdraw an amount of asset from the platform.
* @param _recipient Address to which the asset should be sent
* @param _asset Address of the asset
* @param _amount Units of asset to withdraw
* @return amountWithdrawn Quantity of asset that was withdrawn
*/
function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external returns (uint256 amountWithdrawn);
/**
* @dev Liquidate entire contents of strategy sending assets to Vault.
*/
function liquidate() external;
/**
* @dev Get the total asset value held in the platform.
* This includes any interest that was generated since depositing.
* @param _asset Address of the asset
* @return balance Total value of the asset in the platform
*/
function checkBalance(address _asset)
external
view
returns (uint256 balance);
/**
* @dev Check if an asset is supported.
* @param _asset Address of the asset
* @return bool Whether asset is supported
*/
function supportsAsset(address _asset) external view returns (bool);
/**
* @dev Get the weighted APR for all assets.
* @return uint256 APR for Strategy
*/
function getAPR() external view returns (uint256);
/**
* @dev Get the APR for a single asset.
* @param _asset Address of the asset
* @return uint256 APR for single asset in Strategy
*/
function getAssetAPR(address _asset) external view returns (uint256);
}
contract CompoundStrategy is InitializableAbstractStrategy {
event RewardTokenCollected(address recipient, uint256 amount);
event SkippedWithdrawal(address asset, uint256 amount);
/**
* @dev Collect accumulated reward token (COMP) and send to Vault.
*/
function collectRewardToken() external onlyVault {
IERC20 compToken = IERC20(rewardTokenAddress);
uint256 balance = compToken.balanceOf(address(this));
require(
compToken.transfer(vaultAddress, balance),
"Reward token transfer failed"
);
emit RewardTokenCollected(vaultAddress, balance);
}
/**
* @dev Deposit asset into Compound
* @param _asset Address of asset to deposit
* @param _amount Amount of asset to deposit
* @return amountDeposited Amount of asset that was deposited
*/
function deposit(address _asset, uint256 _amount)
external
onlyVault
returns (uint256 amountDeposited)
{
require(_amount > 0, "Must deposit something");
ICERC20 cToken = _getCTokenFor(_asset);
require(cToken.mint(_amount) == 0, "cToken mint failed");
amountDeposited = _amount;
emit Deposit(_asset, address(cToken), amountDeposited);
}
/**
* @dev Withdraw asset from Compound
* @param _recipient Address to receive withdrawn asset
* @param _asset Address of asset to withdraw
* @param _amount Amount of asset to withdraw
* @return amountWithdrawn Amount of asset that was withdrawn
*/
function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external onlyVault returns (uint256 amountWithdrawn) {
require(_amount > 0, "Must withdraw something");
require(_recipient != address(0), "Must specify recipient");
ICERC20 cToken = _getCTokenFor(_asset);
// If redeeming 0 cTokens, just skip, else COMP will revert
uint256 cTokensToRedeem = _convertUnderlyingToCToken(cToken, _amount);
if (cTokensToRedeem == 0) {
emit SkippedWithdrawal(_asset, _amount);
return 0;
}
amountWithdrawn = _amount;
require(cToken.redeemUnderlying(_amount) == 0, "Redeem failed");
IERC20(_asset).safeTransfer(_recipient, amountWithdrawn);
emit Withdrawal(_asset, address(cToken), amountWithdrawn);
}
/**
* @dev Remove all assets from platform and send them to Vault contract.
*/
function liquidate() external onlyVaultOrGovernor {
for (uint256 i = 0; i < assetsMapped.length; i++) {
// Redeem entire balance of cToken
ICERC20 cToken = _getCTokenFor(assetsMapped[i]);
if (cToken.balanceOf(address(this)) > 0) {
cToken.redeem(cToken.balanceOf(address(this)));
// Transfer entire balance to Vault
IERC20 asset = IERC20(assetsMapped[i]);
asset.safeTransfer(
vaultAddress,
asset.balanceOf(address(this))
);
}
}
}
/**
* @dev Get the total asset value held in the platform
* This includes any interest that was generated since depositing
* Compound exchange rate between the cToken and asset gradually increases,
* causing the cToken to be worth more corresponding asset.
* @param _asset Address of the asset
* @return balance Total value of the asset in the platform
*/
function checkBalance(address _asset)
external
view
returns (uint256 balance)
{
// Balance is always with token cToken decimals
ICERC20 cToken = _getCTokenFor(_asset);
balance = _checkBalance(cToken);
}
/**
* @dev Get the total asset value held in the platform
* underlying = (cTokenAmt * exchangeRate) / 1e18
* @param _cToken cToken for which to check balance
* @return balance Total value of the asset in the platform
*/
function _checkBalance(ICERC20 _cToken)
internal
view
returns (uint256 balance)
{
uint256 cTokenBalance = _cToken.balanceOf(address(this));
uint256 exchangeRate = _cToken.exchangeRateStored();
// e.g. 50e8*205316390724364402565641705 / 1e18 = 1.0265..e18
balance = cTokenBalance.mul(exchangeRate).div(1e18);
}
/**
* @dev Retuns bool indicating whether asset is supported by strategy
* @param _asset Address of the asset
*/
function supportsAsset(address _asset) external view returns (bool) {
return assetToPToken[_asset] != address(0);
}
/**
* @dev Approve the spending of all assets by their corresponding cToken,
* if for some reason is it necessary. Only callable through Governance.
*/
function safeApproveAllTokens() external {
uint256 assetCount = assetsMapped.length;
for (uint256 i = 0; i < assetCount; i++) {
address asset = assetsMapped[i];
address cToken = assetToPToken[asset];
// Safe approval
IERC20(asset).safeApprove(cToken, 0);
IERC20(asset).safeApprove(cToken, uint256(-1));
}
}
/**
* @dev Get the weighted APR for all assets in strategy.
* @return APR in 1e18
*/
function getAPR() external view returns (uint256) {
uint256 totalValue = 0;
for (uint256 i = 0; i < assetsMapped.length; i++) {
ICERC20 cToken = _getCTokenFor(assetsMapped[i]);
totalValue += _checkBalance(cToken);
}
if (totalValue == 0) return 0;
uint256 totalAPR = 0;
for (uint256 i = 0; i < assetsMapped.length; i++) {
ICERC20 cToken = _getCTokenFor(assetsMapped[i]);
totalAPR += _checkBalance(cToken)
.mul(_getAssetAPR(assetsMapped[i]))
.div(totalValue);
}
return totalAPR;
}
/**
* @dev Get the APR for a single asset.
* @param _asset Address of the asset
* @return APR in 1e18
*/
function getAssetAPR(address _asset) external view returns (uint256) {
return _getAssetAPR(_asset);
}
/**
* @dev Internal method to get the APR for a single asset.
* @param _asset Address of the asset
* @return APR in 1e18
*/
function _getAssetAPR(address _asset) internal view returns (uint256) {
ICERC20 cToken = _getCTokenFor(_asset);
// Extrapolate to a year assuming 6,500 blocks per day times 365.
return cToken.supplyRatePerBlock().mul(2372500);
}
/**
* @dev Internal method to respond to the addition of new asset / cTokens
* We need to approve the cToken and give it permission to spend the asset
* @param _asset Address of the asset to approve
* @param _cToken This cToken has the approval approval
*/
function _abstractSetPToken(address _asset, address _cToken) internal {
// Safe approval
IERC20(_asset).safeApprove(_cToken, 0);
IERC20(_asset).safeApprove(_cToken, uint256(-1));
}
/**
* @dev Get the cToken wrapped in the ICERC20 interface for this asset.
* Fails if the pToken doesn't exist in our mappings.
* @param _asset Address of the asset
* @return Corresponding cToken to this asset
*/
function _getCTokenFor(address _asset) internal view returns (ICERC20) {
address cToken = assetToPToken[_asset];
require(cToken != address(0), "cToken does not exist");
return ICERC20(cToken);
}
/**
* @dev Converts an underlying amount into cToken amount
* cTokenAmt = (underlying * 1e18) / exchangeRate
* @param _cToken cToken for which to change
* @param _underlying Amount of underlying to convert
* @return amount Equivalent amount of cTokens
*/
function _convertUnderlyingToCToken(ICERC20 _cToken, uint256 _underlying)
internal
view
returns (uint256 amount)
{
uint256 exchangeRate = _cToken.exchangeRateStored();
// e.g. 1e18*1e18 / 205316390724364402565641705 = 50e8
// e.g. 1e8*1e18 / 205316390724364402565641705 = 0.45 or 0
amount = _underlying.mul(1e18).div(exchangeRate);
}
}
|
Deposit asset into Compound _asset Address of asset to deposit _amount Amount of asset to deposit return amountDeposited Amount of asset that was deposited/
|
function deposit(address _asset, uint256 _amount)
external
onlyVault
returns (uint256 amountDeposited)
{
require(_amount > 0, "Must deposit something");
ICERC20 cToken = _getCTokenFor(_asset);
require(cToken.mint(_amount) == 0, "cToken mint failed");
amountDeposited = _amount;
emit Deposit(_asset, address(cToken), amountDeposited);
}
| 2,121,729 |
contract CapCoinInternational {
/* Public variables of the token */
string public standard = 'Token 0.1';
string public name;
string public symbol;
uint8 public decimals;
uint256 public initialSupply;
uint256 public totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* Initializes contract with initial supply tokens to the creator of the contract */
function CapCoinInternational () {
initialSupply = 500000000;
name ="CapCoinInternational";
decimals = 0;
symbol = "CAPI";
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
}
/* This unnamed function is called whenever someone tries to send ether to it */
function () {
throw; // Prevents accidental sending of ether
}
}
|
Public variables of the token / This creates an array with all balances / Initializes contract with initial supply tokens to the creator of the contract /
|
function CapCoinInternational () {
initialSupply = 500000000;
name ="CapCoinInternational";
decimals = 0;
symbol = "CAPI";
}
| 14,809,564 |
// SPDX-License-Identifier: MIT-open-group
pragma solidity ^0.8.11;
import "contracts/libraries/math/CryptoLibrary.sol";
import "contracts/utils/AtomicCounter.sol";
import "contracts/interfaces/IValidatorPool.sol";
import "contracts/interfaces/IETHDKG.sol";
import "contracts/interfaces/IETHDKGEvents.sol";
import "contracts/interfaces/IProxy.sol";
import "contracts/libraries/ethdkg/ETHDKGStorage.sol";
import "contracts/utils/ETHDKGUtils.sol";
import "contracts/utils/ImmutableAuth.sol";
contract ETHDKGMock is
ETHDKGStorage,
IETHDKG,
ETHDKGUtils,
ImmutableETHDKGAccusations,
ImmutableETHDKGPhases,
IETHDKGEvents
{
address internal immutable _ethdkgAccusations;
address internal immutable _ethdkgPhases;
constructor() ETHDKGStorage() ImmutableETHDKGAccusations() ImmutableETHDKGPhases() {
// bytes32("ETHDKGPhases") = 0x455448444b475068617365730000000000000000000000000000000000000000;
address ethdkgPhases = IProxy(_ETHDKGPhasesAddress()).getImplementationAddress();
assembly {
if iszero(extcodesize(ethdkgPhases)) {
mstore(0x00, "ethdkgPhases size 0")
revert(0x00, 0x20)
}
}
_ethdkgPhases = ethdkgPhases;
// bytes32("ETHDKGAccusations") = 0x455448444b4741636375736174696f6e73000000000000000000000000000000;
address ethdkgAccusations = IProxy(_ETHDKGAccusationsAddress()).getImplementationAddress();
assembly {
if iszero(extcodesize(ethdkgAccusations)) {
mstore(0x00, "ethdkgAccusations size 0")
revert(0x00, 0x20)
}
}
_ethdkgAccusations = ethdkgAccusations;
}
function initialize(uint256 phaseLength_, uint256 confirmationLength_) public initializer {
_phaseLength = uint16(phaseLength_);
_confirmationLength = uint16(confirmationLength_);
}
modifier onlyValidator() {
require(
IValidatorPool(_ValidatorPoolAddress()).isValidator(msg.sender),
"ETHDKG: Only validators allowed!"
);
_;
}
function setPhaseLength(uint16 phaseLength_) external {
require(
!_isETHDKGRunning(),
"ETHDKG: This variable cannot be set if an ETHDKG round is running!"
);
_phaseLength = phaseLength_;
}
function setConfirmationLength(uint16 confirmationLength_) external {
require(
!_isETHDKGRunning(),
"ETHDKG: This variable cannot be set if an ETHDKG round is running!"
);
_confirmationLength = confirmationLength_;
}
function setCustomMadnetHeight(uint256 madnetHeight) external {
_customMadnetHeight = madnetHeight;
emit ValidatorSetCompleted(
0,
_nonce,
ISnapshots(_SnapshotsAddress()).getEpoch(),
ISnapshots(_SnapshotsAddress()).getCommittedHeightFromLatestSnapshot(),
madnetHeight,
0x0,
0x0,
0x0,
0x0
);
}
function isETHDKGRunning() public view returns (bool) {
return _isETHDKGRunning();
}
function _isETHDKGRunning() internal view returns (bool) {
// Handling initial case
if (_phaseStartBlock == 0) {
return false;
}
return !_isETHDKGCompleted() && !_isETHDKGHalted();
}
function isETHDKGCompleted() public view returns (bool) {
return _isETHDKGCompleted();
}
function _isETHDKGCompleted() internal view returns (bool) {
return _ethdkgPhase == Phase.Completion;
}
function isETHDKGHalted() public view returns (bool) {
return _isETHDKGHalted();
}
// todo: generate truth table
function _isETHDKGHalted() internal view returns (bool) {
bool ethdkgFailedInDisputePhase = (_ethdkgPhase == Phase.DisputeShareDistribution ||
_ethdkgPhase == Phase.DisputeGPKJSubmission) &&
block.number >= _phaseStartBlock + _phaseLength &&
_badParticipants != 0;
bool ethdkgFailedInNormalPhase = block.number >= _phaseStartBlock + 2 * _phaseLength;
return ethdkgFailedInNormalPhase || ethdkgFailedInDisputePhase;
}
function isMasterPublicKeySet() public view returns (bool) {
return ((_masterPublicKey[0] != 0) ||
(_masterPublicKey[1] != 0) ||
(_masterPublicKey[2] != 0) ||
(_masterPublicKey[3] != 0));
}
function getNonce() public view returns (uint256) {
return _nonce;
}
function getPhaseStartBlock() public view returns (uint256) {
return _phaseStartBlock;
}
function getPhaseLength() public view returns (uint256) {
return _phaseLength;
}
function getConfirmationLength() public view returns (uint256) {
return _confirmationLength;
}
function getETHDKGPhase() public view returns (Phase) {
return _ethdkgPhase;
}
function getNumParticipants() public view returns (uint256) {
return _numParticipants;
}
function getBadParticipants() public view returns (uint256) {
return _badParticipants;
}
function getMinValidators() public pure returns (uint256) {
return MIN_VALIDATOR;
}
function getParticipantInternalState(address participant)
public
view
returns (Participant memory)
{
return _participants[participant];
}
function getParticipantsInternalState(address[] calldata participantAddresses)
public
view
returns (Participant[] memory)
{
Participant[] memory participants = new Participant[](participantAddresses.length);
for (uint256 i = 0; i < participantAddresses.length; i++) {
participants[i] = _participants[participantAddresses[i]];
}
return participants;
}
function tryGetParticipantIndex(address participant) public view returns (bool, uint256) {
Participant memory participantData = _participants[participant];
if (participantData.nonce == _nonce && _nonce != 0) {
return (true, _participants[participant].index);
}
return (false, 0);
}
function getMasterPublicKey() public view returns (uint256[4] memory) {
return _masterPublicKey;
}
function initializeETHDKG() external {
_initializeETHDKG();
}
function _callAccusationContract(bytes memory callData) internal returns (bytes memory) {
(bool success, bytes memory returnData) = _ethdkgAccusations.delegatecall(callData);
if (!success) {
// solhint-disable no-inline-assembly
assembly {
let ptr := mload(0x40)
let size := returndatasize()
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
}
return returnData;
}
function _callPhaseContract(bytes memory callData) internal returns (bytes memory) {
(bool success, bytes memory returnData) = _ethdkgPhases.delegatecall(callData);
if (!success) {
// solhint-disable no-inline-assembly
assembly {
let ptr := mload(0x40)
let size := returndatasize()
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
}
return returnData;
}
function _initializeETHDKG() internal {
//todo: should we reward ppl here?
uint256 numberValidators = IValidatorPool(_ValidatorPoolAddress()).getValidatorsCount();
require(
numberValidators >= MIN_VALIDATOR,
"ETHDKG: Minimum number of validators staked not met!"
);
_phaseStartBlock = uint64(block.number);
_nonce++;
_numParticipants = 0;
_badParticipants = 0;
_mpkG1 = [uint256(0), uint256(0)];
_ethdkgPhase = Phase.RegistrationOpen;
delete _masterPublicKey;
emit RegistrationOpened(
block.number,
numberValidators,
_nonce,
_phaseLength,
_confirmationLength
);
}
function register(uint256[2] memory publicKey) external onlyValidator {
_callPhaseContract(abi.encodeWithSignature("register(uint256[2])", publicKey));
}
function accuseParticipantNotRegistered(address[] memory dishonestAddresses) external {
_callAccusationContract(
abi.encodeWithSignature("accuseParticipantNotRegistered(address[])", dishonestAddresses)
);
}
function distributeShares(uint256[] memory encryptedShares, uint256[2][] memory commitments)
external
onlyValidator
{
_callPhaseContract(
abi.encodeWithSignature(
"distributeShares(uint256[],uint256[2][])",
encryptedShares,
commitments
)
);
}
///
function accuseParticipantDidNotDistributeShares(address[] memory dishonestAddresses) external {
_callAccusationContract(
abi.encodeWithSignature(
"accuseParticipantDidNotDistributeShares(address[])",
dishonestAddresses
)
);
}
// Someone sent bad shares
function accuseParticipantDistributedBadShares(
address dishonestAddress,
uint256[] memory encryptedShares,
uint256[2][] memory commitments,
uint256[2] memory sharedKey,
uint256[2] memory sharedKeyCorrectnessProof
) external onlyValidator {
_callAccusationContract(
abi.encodeWithSignature(
"accuseParticipantDistributedBadShares(address,uint256[],uint256[2][],uint256[2],uint256[2])",
dishonestAddress,
encryptedShares,
commitments,
sharedKey,
sharedKeyCorrectnessProof
)
);
}
function submitKeyShare(
uint256[2] memory keyShareG1,
uint256[2] memory keyShareG1CorrectnessProof,
uint256[4] memory keyShareG2
) external onlyValidator {
_callPhaseContract(
abi.encodeWithSignature(
"submitKeyShare(uint256[2],uint256[2],uint256[4])",
keyShareG1,
keyShareG1CorrectnessProof,
keyShareG2
)
);
}
function accuseParticipantDidNotSubmitKeyShares(address[] memory dishonestAddresses) external {
_callAccusationContract(
abi.encodeWithSignature(
"accuseParticipantDidNotSubmitKeyShares(address[])",
dishonestAddresses
)
);
}
function submitMasterPublicKey(uint256[4] memory masterPublicKey_) external {
_callPhaseContract(
abi.encodeWithSignature("submitMasterPublicKey(uint256[4])", masterPublicKey_)
);
}
function submitGPKJ(uint256[4] memory gpkj) external onlyValidator {
_callPhaseContract(abi.encodeWithSignature("submitGPKJ(uint256[4])", gpkj));
}
function accuseParticipantDidNotSubmitGPKJ(address[] memory dishonestAddresses) external {
_callAccusationContract(
abi.encodeWithSignature(
"accuseParticipantDidNotSubmitGPKJ(address[])",
dishonestAddresses
)
);
}
function accuseParticipantSubmittedBadGPKJ(
address[] memory validators,
bytes32[] memory encryptedSharesHash,
uint256[2][][] memory commitments,
address dishonestAddress
) external onlyValidator {
_callAccusationContract(
abi.encodeWithSignature(
"accuseParticipantSubmittedBadGPKJ(address[],bytes32[],uint256[2][][],address)",
validators,
encryptedSharesHash,
commitments,
dishonestAddress
)
);
}
// Successful_Completion should be called at the completion of the DKG algorithm.
function complete() external {
_callPhaseContract(abi.encodeWithSignature("complete()"));
}
function minorSlash(address validator, address accussator) external {
IValidatorPool(_ValidatorPoolAddress()).minorSlash(validator, accussator);
}
function majorSlash(address validator, address accussator) external {
IValidatorPool(_ValidatorPoolAddress()).majorSlash(validator, accussator);
}
function setConsensusRunning() external {
IValidatorPool(_ValidatorPoolAddress()).completeETHDKG();
}
}
|
todo: generate truth table
|
function _isETHDKGHalted() internal view returns (bool) {
bool ethdkgFailedInDisputePhase = (_ethdkgPhase == Phase.DisputeShareDistribution ||
_ethdkgPhase == Phase.DisputeGPKJSubmission) &&
block.number >= _phaseStartBlock + _phaseLength &&
_badParticipants != 0;
bool ethdkgFailedInNormalPhase = block.number >= _phaseStartBlock + 2 * _phaseLength;
return ethdkgFailedInNormalPhase || ethdkgFailedInDisputePhase;
}
| 1,826,902 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
contract DistributedDictionaryMinimal {
constructor(){
initWithWords();
}
struct Post {
uint id;
string wordMeaning;
int votes;
address author;
}
struct Word{
Post[] posts;
}
mapping (string => Word) private wordsMap;
string[] private wordsArray; // mapping does not preserve original words, so we also have words as array.
// ---------- ---------- state changing functions ---------- ----------
function addPost(string memory newWord, string memory wordMeaning) public{
// adds Post to a word, crates word if not exists
// add word if not exists
if(!isWordExists(newWord)){
wordsArray.push(newWord);
}
// create post
Post memory newPost = Post(
{
wordMeaning: wordMeaning,
author: msg.sender,
votes: 0,
id: wordsMap[newWord].posts.length
}
);
// add new post to word map
wordsMap[newWord].posts.push(newPost);
}
function votePost(string memory word, uint votePostId, bool voteType) public{
// up or down votes a post
for (uint i = 0; i < wordsMap[word].posts.length; i++) {
if(wordsMap[word].posts[i].id == votePostId){
if(voteType){
wordsMap[word].posts[i].votes += 1;
}
else{
wordsMap[word].posts[i].votes -= 1;
}
break;
}
}
}
// ---------- ---------- ---------- ---------- ----------
// ---------- ---------- post getters ---------- ----------
function getPostsByWord(string memory word) view public returns (Post[] memory){
// returnes posts for a word
return wordsMap[word].posts;
}
// ---------- ---------- ---------- ---------- ----------
// ---------- ---------- word getters ---------- ----------
function getWordsBetween(uint start, uint end) view public returns (string[] memory){
// returnes words in between a range
string[] memory temp = new string[](end - start);
uint j = 0;
for (uint i = start; i < end; i++) {
temp[j] = wordsArray[i];
j++;
}
return temp;
}
function getAllWords() view public returns (string[] memory){
// returnes all saved words
return wordsArray;
}
function getWordCount() view public returns (uint){
// returnes word array length
return wordsArray.length;
}
function isWordExists(string memory word) view public returns (bool){
// returnes true if a word exists
if(wordsMap[word].posts.length > 0){
return true;
}
else{
return false;
}
}
// ---------- ---------- ---------- ---------- ----------
// ---------- ---------- other ---------- ----------
function initWithWords() private {
// for initialising contract with words
addPost("Distributed Dictionary", "A user-created dictionary that runs entirely on the blockchain without the need for a centralized backend.");
}
// ---------- ---------- ---------- ---------- ----------
}
|
returnes word array length
|
function getWordCount() view public returns (uint){
return wordsArray.length;
}
| 5,546,789 |
/**
*Submitted for verification at Etherscan.io on 2022-03-21
*/
// Sources flattened with hardhat v2.9.1 https://hardhat.org
// File @openzeppelin/contracts/utils/[email protected]
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/access/[email protected]
// : MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// File @openzeppelin/contracts/utils/[email protected]
// : MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/utils/[email protected]
// : MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
// : MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
// : MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File @openzeppelin/contracts/access/[email protected]
// : MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
// : MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts/token/ERC1155/[email protected]
// : MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* 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 safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// File contracts/IStandarERC721.sol
// : MIT
pragma solidity ^0.8.9;
/**
* @title NFTBridge
*/
interface IStandarERC721 {
function mint(address _to, uint256 _tokenId) external;
}
// File contracts/IStandarERC1155.sol
// : MIT
pragma solidity ^0.8.9;
/**
* @title NFTBridge
*/
interface IStandarERC1155 {
function mint(address to, uint256 id, uint256 amount, bytes memory data) external;
}
// File contracts/gateway/ICrossDomainMessenger.sol
// : MIT
pragma solidity >0.5.0 <0.9.0;
/**
* @title ICrossDomainMessenger
*/
interface ICrossDomainMessenger {
/**********
* Events *
**********/
event SentMessage(
address indexed target,
address sender,
bytes message,
uint256 messageNonce,
uint256 gasLimit,
uint256 chainId
);
event RelayedMessage(bytes32 indexed msgHash);
event FailedRelayedMessage(bytes32 indexed msgHash);
/*************
* Variables *
*************/
function xDomainMessageSender() external view returns (address);
/********************
* Public Functions *
********************/
/**
* Sends a cross domain message to the target messenger.
* @param _target Target contract address.
* @param _message Message to send to the target.
* @param _gasLimit Gas limit for the provided message.
*/
function sendMessage(
address _target,
bytes calldata _message,
uint32 _gasLimit
) external payable;
/**
* Sends a cross domain message to the target messenger.
* @param _chainId L2 chain id.
* @param _target Target contract address.
* @param _message Message to send to the target.
* @param _gasLimit Gas limit for the provided message.
*/
function sendMessageViaChainId(
uint256 _chainId,
address _target,
bytes calldata _message,
uint32 _gasLimit
) external payable;
}
// File contracts/gateway/CrossDomainEnabled.sol
// : MIT
pragma solidity >0.5.0 <0.9.0;
/* Interface Imports */
/**
* @title CrossDomainEnabled
* @dev Helper contract for contracts performing cross-domain communications
*
* Compiler used: defined by inheriting contract
* Runtime target: defined by inheriting contract
*/
contract CrossDomainEnabled {
/*************
* Variables *
*************/
// Messenger contract used to send and recieve messages from the other domain.
address public messenger;
/***************
* Constructor *
***************/
/**
* @param _messenger Address of the CrossDomainMessenger on the current layer.
*/
constructor(address _messenger) {
messenger = _messenger;
}
/**********************
* Function Modifiers *
**********************/
/**
* Enforces that the modified function is only callable by a specific cross-domain account.
* @param _sourceDomainAccount The only account on the originating domain which is
* authenticated to call this function.
*/
modifier onlyFromCrossDomainAccount(address _sourceDomainAccount) {
require(
msg.sender == address(getCrossDomainMessenger()),
"OVM_XCHAIN: messenger contract unauthenticated"
);
require(
getCrossDomainMessenger().xDomainMessageSender() == _sourceDomainAccount,
"OVM_XCHAIN: wrong sender of cross-domain message"
);
_;
}
/**********************
* Internal Functions *
**********************/
/**
* Gets the messenger, usually from storage. This function is exposed in case a child contract
* needs to override.
* @return The address of the cross-domain messenger contract which should be used.
*/
function getCrossDomainMessenger() internal virtual returns (ICrossDomainMessenger) {
return ICrossDomainMessenger(messenger);
}
/**q
* Sends a message to an account on another domain
* @param _crossDomainTarget The intended recipient on the destination domain
* @param _message The data to send to the target (usually calldata to a function with
* `onlyFromCrossDomainAccount()`)
* @param _gasLimit The gasLimit for the receipt of the message on the target domain.
*/
function sendCrossDomainMessage(
address _crossDomainTarget,
uint32 _gasLimit,
bytes memory _message,
uint256 fee
)
internal
{
getCrossDomainMessenger().sendMessage{value:fee}(_crossDomainTarget, _message, _gasLimit);
}
/**
* @notice Sends a message to an account on another domain
* @param _chainId L2 chain id.
* @param _crossDomainTarget The intended recipient on the destination domain
* @param _gasLimit The gasLimit for the receipt of the message on the target domain.
* @param _message The data to send to the target (usually calldata to a function with `onlyFromCrossDomainAccount()`)
*/
function sendCrossDomainMessageViaChainId(
uint256 _chainId,
address _crossDomainTarget,
uint32 _gasLimit,
bytes memory _message,
uint256 fee
) internal {
getCrossDomainMessenger().sendMessageViaChainId{value:fee}(_chainId, _crossDomainTarget, _message, _gasLimit);
}
}
// File contracts/ICrollDomain.sol
// : MIT
pragma solidity ^0.8.9;
/**
* @title ICrollDomain
*/
interface ICrollDomain {
function finalizeDeposit(address _nft, address _from, address _to, uint256 _id, uint256 _amount, uint8 nftStandard) external;
}
// File contracts/ICrollDomainConfig.sol
// : MIT
pragma solidity ^0.8.9;
/**
* @title ICrollDomainConfig
*/
interface ICrollDomainConfig {
function configNFT(address L1NFT, address L2NFT, uint256 originNFTChainId) external;
}
// File contracts/CommonEvent.sol
// : MIT
pragma solidity ^0.8.9;
/**
* @title CommonEvent
*/
interface CommonEvent {
event EVENT_SET(
address indexed _deposit,
address indexed _bridge
);
event CONFIT_NFT(
address indexed _localNFT,
address indexed _destNFT,
uint256 _chainID
);
event DEPOSIT_TO(
address _nft,
address _from,
address _to,
uint256 _tokenID,
uint256 _amount,
uint8 nftStandard
);
event FINALIZE_DEPOSIT(
address _nft,
address _from,
address _to,
uint256 _tokenID,
uint256 _amount,
uint8 nftStandard
);
event DEPOSIT_FAILED(
address _nft,
address _from,
address _to,
uint256 _tokenID,
uint256 _amount,
uint8 nftStandard
);
event ROLLBACK(
address _nft,
address _from,
address _to,
uint256 _tokenID,
uint256 _amount,
uint8 nftStandard
);
}
// File contracts/INFTDeposit.sol
// : MIT
pragma solidity ^0.8.9;
/**
* @title NFTBridge
*/
interface INFTDeposit {
function withdrawERC721(
address _nft,
address _to,
uint256 _tokenId
)
external;
function withdrawERC1155(
address _nft,
address _to,
uint256 _tokenId,
uint256 _amount
)
external;
}
// File contracts/gateway/iMVM_DiscountOracle.sol
// : MIT
pragma solidity ^0.8.9;
interface iMVM_DiscountOracle{
function setDiscount(
uint256 _discount
) external;
function setMinL2Gas(
uint256 _minL2Gas
) external;
function setWhitelistedXDomainSender(
address _sender,
bool _isWhitelisted
) external;
function isXDomainSenderAllowed(
address _sender
) view external returns(bool);
function setAllowAllXDomainSenders(
bool _allowAllXDomainSenders
) external;
function getMinL2Gas() view external returns(uint256);
function getDiscount() view external returns(uint256);
function processL2SeqGas(address sender, uint256 _chainId) external payable;
}
// File contracts/gateway/iLib_AddressManager.sol
// : MIT
pragma solidity ^0.8.9;
interface iLib_AddressManager {
/**
* Retrieves the address associated with a given name.
* @param _name Name to retrieve an address for.
* @return Address associated with the given name.
*/
function getAddress(string memory _name) external view returns (address);
}
// File contracts/L1/L1NFTBridge.sol
// : MIT
pragma solidity ^0.8.0;
contract L1NFTBridge is CrossDomainEnabled, AccessControl, CommonEvent {
// L1 configNFT role
bytes32 public constant NFT_FACTORY_ROLE = keccak256("NFT_FACTORY_ROLE");
// rollback
bytes32 public constant ROLLBACK_ROLE = keccak256("ROLLBACK_ROLE");
// L2 bridge
address public destNFTBridge;
// L1 deposit
address public localNFTDeposit;
// L1 preset address manager
address public addressManager;
// L1 preset oracle
iMVM_DiscountOracle public oracle;
// L2 chainid
uint256 public DEST_CHAINID = 1088;
// get current chainid
function getChainID() internal view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
// nft supported
enum nftenum {
ERC721,
ERC1155
}
function setL2ChainID(uint256 chainID) public onlyRole(DEFAULT_ADMIN_ROLE) {
DEST_CHAINID = chainID;
}
// L1 nft => L2 nft
mapping(address => address) public clone;
// L1 nft => is the original
mapping(address => bool) public isOrigin;
// L1 nft => L1 nft id => is deposited
mapping(address => mapping( uint256 => bool )) public isDeposit;
// L1 nft => L1 nft id => deposit user
mapping(address => mapping( uint256 => address )) public depositUser;
modifier onlyEOA() {
require(!Address.isContract(msg.sender), "Account not EOA");
_;
}
/**
* @param _owner admin role
* @param _nftFactory factory role
* @param _addressManager pre deploy iLib_AddressManager
* @param _localMessenger pre deploy messenger
* @param _rollback rollback role
*/
constructor(address _owner, address _nftFactory, address _rollback, address _addressManager, address _localMessenger) CrossDomainEnabled(_localMessenger) {
_setupRole(DEFAULT_ADMIN_ROLE, _owner);
_setupRole(NFT_FACTORY_ROLE, _nftFactory);
_setupRole(ROLLBACK_ROLE, _rollback);
addressManager = _addressManager;
oracle = iMVM_DiscountOracle(iLib_AddressManager(addressManager).getAddress('MVM_DiscountOracle'));
}
/** config
*
* @param _localNFTDeposit L1 deposit
* @param _destNFTBridge L2 bridge
*/
function set(address _localNFTDeposit, address _destNFTBridge) public onlyRole(DEFAULT_ADMIN_ROLE){
require(destNFTBridge == address(0), "Already configured.");
localNFTDeposit = _localNFTDeposit;
destNFTBridge = _destNFTBridge;
emit EVENT_SET(localNFTDeposit, destNFTBridge);
}
/** factory role config nft clone
*
* @param localNFT nft on this chain
* @param destNFT nft on L2
* @param originNFTChainId origin NFT ChainId
* @param destGasLimit L2 gas limit
*/
function configNFT(address localNFT, address destNFT, uint256 originNFTChainId, uint32 destGasLimit) external payable onlyRole(NFT_FACTORY_ROLE) {
uint256 localChainId = getChainID();
require((originNFTChainId == DEST_CHAINID || originNFTChainId == localChainId), "ChainId not supported");
require(clone[localNFT] == address(0), "NFT already configured.");
uint32 minGasLimit = uint32(oracle.getMinL2Gas());
if (destGasLimit < minGasLimit) {
destGasLimit = minGasLimit;
}
require(destGasLimit * oracle.getDiscount() <= msg.value, string(abi.encodePacked("insufficient fee supplied. send at least ", uint2str(destGasLimit * oracle.getDiscount()))));
clone[localNFT] = destNFT;
isOrigin[localNFT] = false;
if(localChainId == originNFTChainId){
isOrigin[localNFT] = true;
}
bytes memory message = abi.encodeWithSelector(
ICrollDomainConfig.configNFT.selector,
localNFT,
destNFT,
originNFTChainId
);
sendCrossDomainMessageViaChainId(
DEST_CHAINID,
destNFTBridge,
destGasLimit,
message,
msg.value
);
emit CONFIT_NFT(localNFT, destNFT, originNFTChainId);
}
/** deposit nft into L1 deposit
*
* @param localNFT nft on this chain
* @param destTo owns nft on L2
* @param id nft id
* @param nftStandard nft type
* @param destGasLimit L2 gas limit
*/
function depositTo(address localNFT, address destTo, uint256 id, nftenum nftStandard, uint32 destGasLimit) external onlyEOA() payable {
require(clone[localNFT] != address(0), "NFT not config.");
require(isDeposit[localNFT][id] == false, "Don't redeposit.");
uint32 minGasLimit = uint32(oracle.getMinL2Gas());
if (destGasLimit < minGasLimit) {
destGasLimit = minGasLimit;
}
require(destGasLimit * oracle.getDiscount() <= msg.value, string(abi.encodePacked("insufficient fee supplied. send at least ", uint2str(destGasLimit * oracle.getDiscount()))));
uint256 amount = 0;
if(nftenum.ERC721 == nftStandard) {
IERC721(localNFT).safeTransferFrom(msg.sender, localNFTDeposit, id);
}
if(nftenum.ERC1155 == nftStandard) {
amount = IERC1155(localNFT).balanceOf(msg.sender, id);
require(amount == 1, "Not an NFT token.");
IERC1155(localNFT).safeTransferFrom(msg.sender, localNFTDeposit, id, amount, "");
}
_depositStatus(localNFT, id, msg.sender, true);
address destNFT = clone[localNFT];
_messenger(DEST_CHAINID, destNFT, msg.sender, destTo, id, amount, uint8(nftStandard), destGasLimit);
emit DEPOSIT_TO(destNFT, msg.sender, destTo, id, amount, uint8(nftStandard));
}
function _depositStatus(address _nft, uint256 _id, address _user, bool _isDeposit) internal {
isDeposit[_nft][_id] = _isDeposit;
depositUser[_nft][_id] = _user;
}
/** deposit messenger
*
* @param chainId L2 chainId
* @param destNFT nft on L2
* @param from msg.sender
* @param destTo owns nft on L2
* @param id nft id
* @param amount amount
* @param nftStandard nft type
* @param destGasLimit L2 gas limit
*/
function _messenger(uint256 chainId, address destNFT, address from, address destTo, uint256 id, uint256 amount, uint8 nftStandard, uint32 destGasLimit) internal {
bytes memory message = abi.encodeWithSelector(
ICrollDomain.finalizeDeposit.selector,
destNFT,
from,
destTo,
id,
amount,
nftStandard
);
sendCrossDomainMessageViaChainId(
chainId,
destNFTBridge,
destGasLimit,
message,
msg.value
);
}
/** clone nft
*
* @param _localNFT nft
* @param _destFrom owns nft on l2
* @param _localTo give to
* @param id nft id
* @param _amount nft amount
* @param nftStandard nft type
*/
function finalizeDeposit(address _localNFT, address _destFrom, address _localTo, uint256 id, uint256 _amount, nftenum nftStandard) external onlyFromCrossDomainAccount(destNFTBridge) {
if(nftenum.ERC721 == nftStandard) {
if(isDeposit[_localNFT][id]){
INFTDeposit(localNFTDeposit).withdrawERC721(_localNFT, _localTo, id);
}else{
if(isOrigin[_localNFT]){
// What happened
emit DEPOSIT_FAILED(_localNFT, _destFrom, _localTo, id, _amount, uint8(nftStandard));
}else{
IStandarERC721(_localNFT).mint(_localTo, id);
}
}
}
if(nftenum.ERC1155 == nftStandard) {
if(isDeposit[_localNFT][id]){
INFTDeposit(localNFTDeposit).withdrawERC1155(_localNFT, _localTo, id, _amount);
}else{
if(isOrigin[_localNFT]){
// What happened
emit DEPOSIT_FAILED(_localNFT, _destFrom, _localTo, id, _amount, uint8(nftStandard));
}else{
IStandarERC1155(_localNFT).mint(_localTo, id, _amount, "");
}
}
}
_depositStatus(_localNFT, id, address(0), false);
emit FINALIZE_DEPOSIT(_localNFT, _destFrom, _localTo, id, _amount, uint8(nftStandard));
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
/** hack rollback
*
* @param nftStandard nft type
* @param _localNFT nft
* @param ids tokenid
*/
function rollback(nftenum nftStandard, address _localNFT, uint256[] memory ids) public onlyRole(ROLLBACK_ROLE) {
for( uint256 index; index < ids.length; index++ ){
uint256 id = ids[index];
address _depositUser = depositUser[_localNFT][id];
require(isDeposit[_localNFT][id], "Not Deposited");
require(_depositUser != address(0), "user can not be zero address.");
uint256 amount = 0;
if(nftenum.ERC721 == nftStandard) {
INFTDeposit(localNFTDeposit).withdrawERC721(_localNFT, _depositUser, id);
}else{
amount = 1;
INFTDeposit(localNFTDeposit).withdrawERC1155(_localNFT, _depositUser, id, amount);
}
_depositStatus(_localNFT, id, address(0), false);
emit ROLLBACK(_localNFT, localNFTDeposit, _depositUser, id, amount, uint8(nftStandard));
}
}
}
|
q Sends a message to an account on another domain _crossDomainTarget The intended recipient on the destination domain _message The data to send to the target (usually calldata to a function with `onlyFromCrossDomainAccount()`) _gasLimit The gasLimit for the receipt of the message on the target domain./
|
function sendCrossDomainMessage(
address _crossDomainTarget,
uint32 _gasLimit,
bytes memory _message,
uint256 fee
)
internal
{
}
| 2,180,529 |
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
address private callerContract; // The deployed App contract address which can call this Data Contract
struct Insurance {
uint256 amount;
uint256 claimAmount;
uint8 status;
}
struct Airline {
uint8 id;
string name;
bool consensus;
int8 voteCount;
bool activated;
uint256 balance;
}
uint8 private constant BOUGHT_INSURANCE = 0;
uint8 private constant CLAIMED_INSURANCE = 1;
uint8 private constant WITHDRAWN_INSURANCE = 2;
mapping(bytes32 => Insurance) insurances; // key => Insurance
uint8 totalCountAirlines; // number of airlines
mapping(address => Airline) airlines; // airlineAddress => Airline
mapping(address => mapping(address => bool)) votes; // voterAddress => airlineAddress
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
event ChangedCallerContract(
address indexed oldAddress,
address indexed newAddress
);
/********************************************************************************************/
/* Constructor */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor() {
contractOwner = msg.sender;
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational() {
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner() {
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Modifier that requires the callerContract to be the function caller
*/
modifier requireCallerContract() {
require(
msg.sender == callerContract,
"Caller is not the FlightSuretyApp contract"
);
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational() external view returns (bool) {
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus(bool mode) external requireContractOwner {
operational = mode;
}
/**
* @dev Sets app contract address
*
* This allows contract owner to change app contract address, in case a new app is present
*/
function setCallerContractAddress(address _callerContract) external requireContractOwner {
callerContract = _callerContract;
emit ChangedCallerContract(callerContract, _callerContract);
}
/**
* @dev Get current app contract address
*
* This allows contract owner to fetch current app contract address
*/
function getCallerContract() external view requireContractOwner returns (address) {
return callerContract;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline(address _voterAddress, address addressAirline, string memory _airlineName, bool consensus) external requireIsOperational requireCallerContract {
_vote(_voterAddress, addressAirline);
totalCountAirlines += 1;
// airlines count is incremented
airlines[addressAirline] = Airline({id: totalCountAirlines, name: _airlineName, consensus: consensus, balance: 0, activated: false, voteCount: 1 });
}
/**
* @dev Get details of the airline from its address
*/
function getAirline(address addressAirline) external view
returns (
uint8 id,
string memory name,
bool consensus,
int8 voteCount,
bool activated,
uint256 balance ) {
id = airlines[addressAirline].id;
name = airlines[addressAirline].name;
consensus = airlines[addressAirline].consensus;
voteCount = airlines[addressAirline].voteCount;
activated = airlines[addressAirline].activated;
balance = airlines[addressAirline].balance;
}
/**
* @dev Fund the balance for airline
*/
function addAirlineBalance(address addressAirline, uint256 amount) external requireIsOperational requireCallerContract {
airlines[addressAirline].balance += amount;
}
/**
* @dev Get airline id from its address
*/
function getAirlineId(address addressAirline) external view returns (uint8 id) {
id = airlines[addressAirline].id;
}
/**
* @dev Approve an airline to be a part of this Flight insurance
*/
function approveAirline(address addressAirline) external requireIsOperational requireCallerContract {
airlines[addressAirline].consensus = true;
}
/**
* @dev Get the total number of airlines registered
*/
function getTotalCountAirlines() external view returns (uint8 count) {
count = totalCountAirlines;
}
/**
* @dev Vote for an airline
*/
function voteAirline(address _voterAddress, address addressAirline) external requireIsOperational requireCallerContract returns (int8 voteCount) {
_vote(_voterAddress, addressAirline);
voteCount = airlines[addressAirline].voteCount;
}
/**
* @dev An airline with the given address will be activated
*/
function activateAirline(address addressAirline) external requireIsOperational requireCallerContract {
airlines[addressAirline].activated = true;
}
/**
* @dev Get the insurance details for the passenger and flight
*/
function getInsurance(address _passengerAddr, bytes32 _flightKey) external view
returns (
uint256 amount,
uint256 claimAmount,
uint8 status ) {
bytes32 key = getInsuranceKey(_passengerAddr, _flightKey);
amount = insurances[key].amount;
claimAmount = insurances[key].claimAmount;
status = insurances[key].status;
}
/**
* @dev Withdraws the insurance claimed
*/
function withdrawInsurance(address _passengerAddr, bytes32 _flightKey) external requireIsOperational requireCallerContract {
bytes32 key = getInsuranceKey(_passengerAddr, _flightKey);
insurances[key].status = WITHDRAWN_INSURANCE;
}
/**
* @dev To claim the insurance
*/
function claimInsurance(address _passengerAddr, bytes32 _flightKey, uint256 claimAmount) external requireIsOperational requireCallerContract {
bytes32 key = getInsuranceKey(_passengerAddr, _flightKey);
insurances[key].status = CLAIMED_INSURANCE;
insurances[key].claimAmount = claimAmount;
}
/**
* @dev When a passenger buys an insurance, this function adds the insurance for the passenger
* Called in the app contract when the passenger buys insurance for a particular flight
*/
function addInsurance(address _passengerAddr, bytes32 _flightKey, uint256 amount) external requireIsOperational requireCallerContract {
bytes32 key = getInsuranceKey(_passengerAddr, _flightKey);
// Key is used to keep track of the insurances for a specific passenfer and flight in the insurance mapping
insurances[key] = Insurance({
amount: amount,
claimAmount: 0,
status: BOUGHT_INSURANCE
});
}
/**
* @dev Key is calculated to be unique for each flight by using hashing algorithm
*/
function getInsuranceKey(address _passengerAddr, bytes32 _flightKey) private pure returns (bytes32) {
return keccak256(abi.encodePacked(_passengerAddr, _flightKey));
}
/**
* @dev Voter's vote is added to an airline
*/
function _vote(address _voterAddress, address addressAirline) private {
require(
(totalCountAirlines == 0) || (_voterAddress != addressAirline),
"Can't vote on your own except when the owner creates the contract"
);
// Allows the owner to vote himself when contract is created
require(votes[_voterAddress][addressAirline] == false, "Voter has already voted for this airline");
votes[_voterAddress][addressAirline] = true; // votes mapping is updated to record the voting
airlines[addressAirline].voteCount += 1; // votecount for the airline increased by 1
}
}
|
To claim the insurance/
|
function claimInsurance(address _passengerAddr, bytes32 _flightKey, uint256 claimAmount) external requireIsOperational requireCallerContract {
bytes32 key = getInsuranceKey(_passengerAddr, _flightKey);
insurances[key].status = CLAIMED_INSURANCE;
insurances[key].claimAmount = claimAmount;
}
| 1,015,388 |
./full_match/80001/0xD238dD70E5376DA21274717eaa6053075c8b62b4/sources/contracts/TraderBalanceVault/TraderBalanceVault.sol
|
@inheritdoc ITraderBalanceVault/
|
function useTraderAssets(LockAssetParams calldata _params) external override onlyRole(VAULT_ACCESS_ROLE) {
TraderBalance storage depositedBalance = balances[_params.trader][_params.depositAsset];
if (_params.openType != OpenType.OPEN_BY_ORDER) {
_require(
_params.depositAmount <= depositedBalance.availableBalance,
Errors.INSUFFICIENT_FREE_ASSETS.selector
);
}
if (_params.openType == OpenType.OPEN) {
depositedBalance.availableBalance -= _params.depositAmount;
depositedBalance.lockedBalance -= _params.depositAmount;
depositedBalance.availableBalance -= _params.depositAmount;
depositedBalance.lockedBalance += _params.depositAmount;
}
if (_params.depositReceiver != address(0)) {
_require(_params.depositAsset != NATIVE_CURRENCY, Errors.NATIVE_CURRENCY_CANNOT_BE_ASSET.selector);
TokenTransfersLibrary.doTransferOut(_params.depositAsset, _params.depositReceiver, _params.depositAmount);
}
}
| 9,522,267 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./utils/Ownable.sol";
import "./interfaces/IVoters.sol";
import "./interfaces/IERC677Receiver.sol";
contract SaleDutch is Ownable, ReentrancyGuard, IERC677Receiver {
using SafeERC20 for IERC20;
// Information of each user's participation
struct UserInfo {
// How many tokens the user has provided
uint amount;
// Wether this user has already claimed their share of tokens, defaults to false
bool claimedTokens;
}
// The raising token
IERC20 public paymentToken;
// The offering token
IERC20 public offeringToken;
// The time (unix seconds) when sale starts
uint public startTime;
// The time (unix security) when sale ends
uint public endTime;
// Price to start the sale at (offeringToken per 1e18 of paymentToken)
uint public startPrice;
// Reserve price (as amount per 1e18 of token invested)
uint public endPrice;
// Amount of tokens offered for sale
uint public offeringAmount;
// Maximum a user can contribute
uint public perUserCap;
// Voting token minimum balance to participate
uint public votingMinimum;
// Voting token address
IVoters public votingToken;
// Voting token snapshot id to use for balances (optional)
uint public votingSnapshotId;
// Wether deposits are paused
bool public paused;
// Wether the sale is finalized
bool public finalized;
// Total amount of raising tokens that have already been raised
uint public totalAmount;
// User's participation info
mapping(address => UserInfo) public userInfo;
// Participants list
address[] public addressList;
event Deposit(address indexed user, uint amount);
event HarvestTokens(address indexed user, uint amount);
event HarvestRefund(address indexed user, uint amount);
constructor(
address _paymentToken,
address _offeringToken,
uint _startTime,
uint _endTime,
uint _startPrice,
uint _endPrice,
uint _offeringAmount,
uint _perUserCap,
address _owner
) Ownable(_owner) {
paymentToken = IERC20(_paymentToken);
offeringToken = IERC20(_offeringToken);
startTime = _startTime;
endTime = _endTime;
startPrice = _startPrice;
endPrice = _endPrice;
offeringAmount = _offeringAmount;
perUserCap = _perUserCap;
require(_paymentToken != _offeringToken, 'payment != offering');
require(_startTime > block.timestamp, 'start > now');
require(_startTime < _endTime, 'start < end');
require(_startTime < 10000000000, 'start time not unix');
require(_endTime < 10000000000, 'start time not unix');
require(_startPrice > 0, 'start price > 0');
require(_endPrice > 0, 'end price > 0');
require(_offeringAmount > 0, 'offering amount > 0');
}
function configureVotingToken(uint minimum, address token, uint snapshotId) public onlyOwner {
votingMinimum = minimum;
votingToken = IVoters(token);
votingSnapshotId = snapshotId;
}
function togglePaused() public onlyOwner {
paused = !paused;
}
function finalize() public {
require(msg.sender == owner() || block.timestamp > endTime + 7 days, 'no allowed');
finalized = true;
}
function getAddressListLength() external view returns (uint) {
return addressList.length;
}
function getParams() external view returns (uint, uint, uint, uint, uint, uint, uint, uint, uint, bool, bool) {
return (startTime, endTime, startPrice, endPrice,
offeringAmount, perUserCap, totalAmount,
currentPrice(), clearingPrice(), paused, finalized);
}
function priceChange() public view returns (uint) {
return (startPrice - endPrice) / (endTime - startTime);
}
function currentPrice() public view returns (uint) {
if (block.timestamp <= startTime) return startPrice;
if (block.timestamp >= endTime) return endPrice;
return startPrice - ((block.timestamp - startTime) * priceChange());
}
function tokenPrice() public view returns (uint) {
return (totalAmount * 1e18) / offeringAmount;
}
function clearingPrice() public view returns (uint) {
if (tokenPrice() > currentPrice()) return tokenPrice();
return currentPrice();
}
function saleSuccessful() public view returns (bool) {
return tokenPrice() >= clearingPrice();
}
function commitmentSize(uint amount) public view returns (uint) {
uint max = (offeringAmount * clearingPrice()) / 1e18;
if (totalAmount + amount > max) {
return max - totalAmount;
}
return amount;
}
function _deposit(address user, uint amount) private nonReentrant {
require(!paused, 'paused');
require(block.timestamp >= startTime && block.timestamp <= endTime, 'sale not active');
require(amount > 0, 'need amount > 0');
require(perUserCap == 0 || amount <= perUserCap, 'over per user cap');
require(userInfo[user].amount == 0, 'already participated');
if (votingMinimum > 0) {
if (votingSnapshotId == 0) {
require(votingToken.balanceOf(user) >= votingMinimum, "under minimum locked");
} else {
require(votingToken.balanceOfAt(user, votingSnapshotId) >= votingMinimum, "under minimum locked");
}
}
uint cappedAmount = commitmentSize(amount);
require(cappedAmount > 0, 'sale fully commited');
// Refund user's overpayment
if (amount - cappedAmount > 0) {
paymentToken.transfer(user, amount - cappedAmount);
}
addressList.push(user);
userInfo[user].amount = cappedAmount;
totalAmount += cappedAmount;
emit Deposit(user, cappedAmount);
}
function deposit(uint amount) external {
_transferFrom(msg.sender, amount);
_deposit(msg.sender, amount);
}
function onTokenTransfer(address user, uint amount, bytes calldata _data) external override {
require(msg.sender == address(paymentToken), "onTokenTransfer: not paymentToken");
_deposit(user, amount);
}
function harvestTokens() public nonReentrant {
require(!paused, 'paused');
require(block.timestamp > endTime, 'sale not ended');
if (saleSuccessful()) {
require(finalized, 'not finalized');
require(userInfo[msg.sender].amount > 0, 'have you participated?');
require(!userInfo[msg.sender].claimedTokens, 'already claimed');
uint amount = getOfferingAmount(msg.sender);
require(amount > 0, 'nothing to claim');
offeringToken.safeTransfer(msg.sender, amount);
userInfo[msg.sender].claimedTokens = true;
emit HarvestTokens(msg.sender, amount);
} else {
uint amount = userInfo[msg.sender].amount;
userInfo[msg.sender].amount = 0;
paymentToken.safeTransfer(msg.sender, amount);
emit HarvestRefund(msg.sender, amount);
}
}
// Amount of offering token a user will receive
function getOfferingAmount(address _user) public view returns (uint) {
return (userInfo[_user].amount * offeringAmount) / totalAmount;
}
function withdrawToken(address token, uint amount) public onlyOwner {
IERC20(token).safeTransfer(msg.sender, amount);
}
function _transferFrom(address from, uint amount) private {
uint balanceBefore = paymentToken.balanceOf(address(this));
paymentToken.safeTransferFrom(from, address(this), amount);
uint balanceAfter = paymentToken.balanceOf(address(this));
require(balanceAfter - balanceBefore == amount, "_transferFrom: balance change does not match amount");
}
}
|
Refund user's overpayment
|
function _deposit(address user, uint amount) private nonReentrant {
require(!paused, 'paused');
require(block.timestamp >= startTime && block.timestamp <= endTime, 'sale not active');
require(amount > 0, 'need amount > 0');
require(perUserCap == 0 || amount <= perUserCap, 'over per user cap');
require(userInfo[user].amount == 0, 'already participated');
if (votingMinimum > 0) {
if (votingSnapshotId == 0) {
require(votingToken.balanceOf(user) >= votingMinimum, "under minimum locked");
require(votingToken.balanceOfAt(user, votingSnapshotId) >= votingMinimum, "under minimum locked");
}
}
uint cappedAmount = commitmentSize(amount);
require(cappedAmount > 0, 'sale fully commited');
if (amount - cappedAmount > 0) {
paymentToken.transfer(user, amount - cappedAmount);
}
addressList.push(user);
userInfo[user].amount = cappedAmount;
totalAmount += cappedAmount;
emit Deposit(user, cappedAmount);
}
| 1,834,302 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "../AccountController.sol";
/**
* @title Account controller mock
*
* @author Stanisław Głogowski <[email protected]>
*/
contract AccountControllerMock is AccountController {
/**
* @dev Public constructor
* @param accountRegistry_ account registry address
* @param accountImplementation_ account implementation address
*/
constructor(
address accountRegistry_,
address accountImplementation_
)
public
AccountController()
{
_initializeAccountController(accountRegistry_, accountImplementation_);
}
// external functions
/**
* @notice Sets account registry
* @param accountRegistry_ account registry address
*/
function setAccountRegistry(
address accountRegistry_
)
external
{
_setAccountRegistry(accountRegistry_, true);
}
/**
* @notice Sets account implementation
* @param accountImplementation_ account implementation address
*/
function setAccountImplementation(
address accountImplementation_
)
external
{
_setAccountImplementation(accountImplementation_, true);
}
/**
* @notice Deploys account
* @param salt CREATE2 salt
*/
function deployAccount(
bytes32 salt
)
external
{
_deployAccount(salt, true);
}
/**
* @notice Upgrades account
* @param account account address
*/
function upgradeAccount(
address account
)
external
{
_upgradeAccount(account, true);
}
/**
* @notice Executes transaction from the account
* @param account account address
* @param to to address
* @param value value
* @param data data
*/
function executeAccountTransaction(
address account,
address to,
uint256 value,
bytes memory data
)
external
{
_executeAccountTransaction(account, to, value, data, true);
}
// external functions (views)
/**
* @notice Computes account CREATE2 address
* @param salt CREATE2 salt
* @return account address
*/
function computeAccountAddress(
bytes32 salt
)
external
view
returns (address)
{
return _computeAccountAddress(salt);
}
}
|
Sets account registry accountRegistry_ account registry address/
|
function setAccountRegistry(
address accountRegistry_
)
external
{
_setAccountRegistry(accountRegistry_, true);
}
| 12,832,555 |
//SPDX-License-Identifier: TBD
pragma solidity =0.7.4;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
interface ICoinSwapERC20 is IERC20 {
event Swap(address indexed,uint192,uint192,address indexed);
event Sync(uint);
event Mint(address indexed sender, uint192);
event Burn(address indexed sender, uint192, address indexed to);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
interface ICoinSwapCallee {
function coinswapCall(address sender, uint amount0,uint amount1, bytes calldata data) external;
}
contract CoinSwapERC20 is ICoinSwapERC20 {
using SafeMath for uint;
string public constant override name = 'CoinSwap V1';
string public constant override symbol = 'CSWPLT';//CoinSwap Liquidity Token
uint8 public constant override decimals = 18;
uint public override totalSupply;
mapping(address => uint) public override balanceOf;
mapping(address => mapping(address => uint)) public override allowance;
bytes32 public override DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant override PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public override nonces;
constructor() {
uint chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external override returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external override returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override {
require(deadline >= block.timestamp, 'CSWP:01');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'CSWP:02');
_approve(owner, spender, value);
}
}
contract CoinSwapPair is CoinSwapERC20 {
using SafeMath for uint;
address public patron;
address public factory;
address public token0; // token0 < token1
address public token1;
uint224 private reserve; //reserve0(96) | reserve1(96) | blockTimestampLast(32)
uint private unlocked = 1;
uint public priceCumulative; //=Delta_y/Delta_x: 96-fractional bits; allows overflow
uint224 private circleData;
modifier lock() {
require(unlocked == 1, 'CSWP:1');
unlocked = 0;
_;
unlocked = 1;
}
constructor() {factory = msg.sender; patron=tx.origin;}
function initialize(address _token0, address _token1, uint224 circle) external {
//circle needs to in order of token0<token1
require(circleData == 0, 'CSWP:2');
token0 = _token0;
token1 = _token1;
circleData = circle; // validity of circle should be checked by CoinSwapFactory
}
function ICO(uint224 _circleData) external {
require( (tx.origin==patron) && (circleData >> 216) >0, 'CSWP:3');//to close ICO, set (circleData >> 216) = 0x00
circleData = _circleData;
}
function setPatron(address _patron) external {
require( (tx.origin==patron), 'CSWP:11');
patron = _patron;
}
function getReserves() public view returns (uint224 _reserve, uint224 _circleData) {
_reserve = reserve;
_circleData = circleData;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'CSWP:6');
}
function revisemu(uint192 balance) private returns (uint56 _mu) {
require(balance>0, 'CSWP:4');
uint224 _circleData = circleData;
uint X = uint(balance>>96) * uint16(_circleData >> 72)* uint56(_circleData >> 160);
uint Y = uint(uint96(balance)) * uint16(_circleData >> 56)* uint56(_circleData >> 104);
uint XpY = X + Y;
uint X2pY2 = (X*X) + (Y*Y);
X = XpY*100;
Y = (X*X) + X2pY2 * (10000+ uint16(_circleData>>88));
uint Z= X2pY2 * 20000;
require(Y>Z, 'CSWP:5');
Y = SQRT.sqrt(Y-Z);
Z = Y > X ? X + Y : X-Y;
_mu = uint56(1)+uint56(((10**32)*Z) / X2pY2);
circleData = (_circleData & 0xFF_FFFFFFFFFFFFFF_FFFFFFFFFFFFFF_FFFF_FFFF_FFFF_00000000000000) | uint224(_mu);
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance) private {
uint32 lastTime = uint32(balance);
uint32 deltaTime = uint32(block.timestamp) -lastTime ;
if (deltaTime>0 && lastTime>0) {
uint circle = circleData;
uint lambda0 = uint16(circle >> 72);
uint lambda1 = uint16(circle >> 56);
uint CmulambdaX = 10**34 - (balance>>128) *lambda0*uint56(circle)*uint56(circle >> 160);
uint CmulambdaY = 10**34 - uint96(balance>>32)*lambda1*uint56(circle)*uint56(circle >> 104);
priceCumulative += (((lambda0*CmulambdaX)<< 96)/(lambda1*CmulambdaY)) * deltaTime;
}
reserve = uint224(balance +deltaTime);
emit Sync(balance>>32);
}
function _mintFee(uint56 mu0) private returns (uint56 mu) {
address feeTo = CoinSwapFactory(factory).feeTo();
mu=revisemu(uint192(reserve>>32));
if (mu0>mu) _mint(feeTo, totalSupply.mul(uint(mu0-mu)) / (5*mu0+mu));
}
function mint(address to) external lock returns (uint liquidity) {
uint224 circle = circleData;
uint _totalSupply = totalSupply;
uint224 _reserve = reserve;
uint96 reserve0 = uint96(_reserve >>128);
uint96 reserve1 = uint96(_reserve >>32);
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint scaledBalance0 = balance0* uint56(circle >> 160);
uint scaledBalance1 = balance1* uint56(circle >> 104);
require((scaledBalance0< 2**96) && (scaledBalance1< 2**96)
&& ( scaledBalance0 >=10**16 || scaledBalance1 >=10**16), 'CSWP:7');
if (_totalSupply == 0) {
uint lambda0 = uint16(circle >> 72);
uint lambda1 = uint16(circle >> 56);
liquidity = (scaledBalance0 * lambda0 + scaledBalance1 * lambda1) >> 1;
revisemu(uint192((balance0<<96)|balance1));
} else {
uint56 mu0=_mintFee(uint56(circle));
_totalSupply = totalSupply;
(uint mu, uint _totalS)=(0,0);
if (reserve0==0) {
mu=(uint(mu0) * reserve1) / balance1;
_totalS = _totalSupply.mul(balance1)/reserve1;
} else if (reserve1==0) {
mu=(uint(mu0) * reserve0) / balance0;
_totalS = _totalSupply.mul(balance0)/reserve0;
} else {
(mu, _totalS) = (balance0 * reserve1) < (balance1 * reserve0)?
((uint(mu0) * reserve0) / balance0, _totalSupply.mul(balance0)/reserve0) :
((uint(mu0) * reserve1) / balance1, _totalSupply.mul(balance1)/reserve1) ;
}
liquidity = _totalS - _totalSupply;
circleData = (circle & 0xFF_FFFFFFFFFFFFFF_FFFFFFFFFFFFFF_FFFF_FFFF_FFFF_00000000000000) | uint224(mu);
}
_mint(to, liquidity);
_update(balance0<<128 | balance1<<32 | uint32(_reserve));
emit Mint(msg.sender, uint192((balance0-reserve0)<<96 | (balance1-reserve1)));
}
function burn(address to) external lock returns (uint192 amount) {
uint224 _reserve = reserve;
address _token0 = token0;
address _token1 = token1;
_mintFee(uint56(circleData));
uint _totalSupply = totalSupply;
uint liquidity = balanceOf[address(this)];
uint amount0 = liquidity.mul(uint96(_reserve>>128)) / _totalSupply;
uint amount1 = liquidity.mul(uint96(_reserve>>32)) / _totalSupply;
amount = uint192((amount0<<96)|amount1);
require(amount > 0, 'CSWP:8');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
uint192 combinedBalance = uint192(IERC20(_token0).balanceOf(address(this))<<96 | IERC20(_token1).balanceOf(address(this)));
_update(uint(combinedBalance)<<32 | uint32(_reserve));
if (combinedBalance>0) revisemu(combinedBalance);
emit Burn(msg.sender, amount, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amountOut, address to, bytes calldata data) external lock {
uint amount0Out = (amountOut >> 96);
uint amount1Out = uint(uint96(amountOut));
uint balance0;
uint balance1;
uint _circleData = circleData;
{ // avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require((to != _token0) && (to != _token1), 'CSWP:9');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out);
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out);
if (data.length > 0) ICoinSwapCallee(to).coinswapCall(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
require(balance0*uint56(_circleData >> 160) < 2**96
&& balance1*uint56(_circleData >> 104) < 2**96, 'CSWP:10');
}
uint amountIn0;
uint amountIn1;
uint224 _reserve = reserve;
{// if _reserve0 < amountOut, then should have been reverted above already, so no need to check here
uint96 reserve0 = uint96(_reserve >>128);
uint96 reserve1 = uint96(_reserve >>32);
amountIn0 = balance0 + amount0Out - reserve0;
amountIn1 = balance1 + amount1Out - reserve1;
uint mulambda0 = uint(uint16(_circleData >> 72))*uint56(_circleData)*uint56(_circleData >> 160);
uint mulambda1 = uint(uint16(_circleData >> 56))*uint56(_circleData)*uint56(_circleData >> 104);
uint X=mulambda0*(balance0*1000 - amountIn0*3);
uint Y=mulambda1*(balance1*1000 - amountIn1*3);
require(10**37 > X && 10**37 >Y, 'CSWP:11');
X = 10**37-X;
Y = 10**37-Y;
uint newrSquare = X*X+Y*Y;
X=10**37-(mulambda0 * reserve0*1000);
Y=10**37-(mulambda1 * reserve1*1000);
require(newrSquare<= (X*X+Y*Y), 'CSWP:12');
}
_update(balance0<<128 | balance1<<32 | uint32(_reserve));
emit Swap(msg.sender, uint192(amountIn0<<96 | amountIn1), uint192(amountOut), to);
}
}
contract CoinSwapFactory {
address payable public feeTo;
address payable public feeToSetter;
mapping(address => mapping(address => address)) public getPair;
address[] public allPairs;
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
constructor(address payable _feeToSetter) {
feeToSetter = _feeToSetter;
feeTo = _feeToSetter;
}
function allPairsLength() external view returns (uint) {
return allPairs.length;
}
function createPair(address tokenA, address tokenB, uint224 circle) external returns (address pair) {
require(tx.origin==feeToSetter, 'CSWP:22');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(getPair[token0][token1] == address(0), 'CSWP:20');
require(uint16(circle>>56)>0 && uint16(circle>>72)>0 &&
uint16(circle>>88)>0 && uint16(circle>>88)<=9999
&& uint56(circle>>104)>=1 && uint56(circle>>104)<=10**16
&& uint56(circle>>160)>=1 && uint56(circle>>160)<=10**16, 'CSWP:23');
bytes memory bytecode = type(CoinSwapPair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
CoinSwapPair(pair).initialize(token0, token1, circle);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair;
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function setFeeTo(address payable _feeTo) external {
require(msg.sender == feeToSetter, 'CSWP:21');
feeTo = _feeTo;
}
function setFeeToSetter(address payable _feeToSetter) external {
require(msg.sender == feeToSetter, 'CSWP:22');
feeToSetter = _feeToSetter;
}
}
contract CoinSwapRouterV1 {
using SafeMath for uint;
address public immutable factory;
address public immutable WETH;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'CSWP:30');
_;
}
constructor(address _factory, address _WETH) {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
uint224 circle //lambda0/lambda1 in circle needs in order of token0<token1
) internal virtual returns (uint amountA, uint amountB, address pairForAB) {
pairForAB =CoinSwapFactory(factory).getPair(tokenA, tokenB);
if (pairForAB == address(0)) {
pairForAB= CoinSwapFactory(factory).createPair(tokenA,tokenB,circle);
}
(uint reserveA, uint reserveB,) = CoinSwapLibrary.getReservesAndmu(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else if (reserveA == 0) {
(amountA, amountB) = (0, amountBDesired);
} else if (reserveB == 0) {
(amountA, amountB) = (amountADesired,0);
} else {
uint amountBOptimal = (amountADesired *reserveB) / reserveA;
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'CSWP:31');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = (amountBDesired *reserveA) / reserveB;
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'CSWP:32');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint amtADesired,
uint amtBDesired,
uint amtAMin,
uint amtBMin,
address to,
uint deadline,
uint224 circle
) external virtual ensure(deadline) returns (uint amtA, uint amtB, uint liquidity) {
address pair;
(amtA, amtB, pair) = _addLiquidity(tokenA, tokenB, amtADesired, amtBDesired, amtAMin, amtBMin, circle);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amtA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amtB);
liquidity = CoinSwapPair(pair).mint(to);
}
function addLiquidityETH(
address token,
uint amtTokenDesired,
uint amtTokenMin,
uint amtETHMin,
address to,
uint deadline,
uint224 circle
) external virtual payable ensure(deadline) returns (uint amtToken, uint amtETH, uint liquidity) {
address pair;
(amtToken, amtETH, pair) = _addLiquidity(token,WETH,amtTokenDesired,msg.value,amtTokenMin,amtETHMin,circle);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amtToken);
IWETH(WETH).deposit{value: amtETH}();
assert(IWETH(WETH).transfer(pair, amtETH));
liquidity = CoinSwapPair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amtETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amtETH);
}
// **** REMOVE LIQUIDITY ****
// For OCI market, we do not have specific remove liquidity function
// but one can remove a pair by providing OCI-ed addresses
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amtAMin,
uint amtBMin,
address to,
uint deadline
) public virtual ensure(deadline) returns (uint amountA, uint amountB) {
address pair = CoinSwapLibrary.pairFor(factory, tokenA, tokenB);
CoinSwapPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
uint192 amount = CoinSwapPair(pair).burn(to);
(amountA, amountB) = tokenA < tokenB ? (uint(amount>>96), uint(uint96(amount))) : (uint(uint96(amount)), uint(amount>>96));
require((amountA >= amtAMin) && (amountB >= amtBMin), 'CSWP:33');
}
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual ensure(deadline) returns (uint amountToken, uint amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual returns (uint amountA, uint amountB) {
address pair = CoinSwapLibrary.pairFor(factory, tokenA, tokenB);
uint value = approveMax ? uint(-1) : liquidity;
CoinSwapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
}
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual returns (uint amountToken, uint amountETH) {
address pair = CoinSwapLibrary.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
CoinSwapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual ensure(deadline) returns (uint amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual returns (uint amountETH) {
address pair = CoinSwapLibrary.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
CoinSwapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token, liquidity, amountTokenMin, amountETHMin, to, deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input < output ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? CoinSwapLibrary.pairFor(factory, output, path[i + 2]) : _to;
CoinSwapPair(CoinSwapLibrary.pairFor(factory, input, output)).swap(
uint192((amount0Out<<96) | amount1Out), to, new bytes(0));
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual ensure(deadline) returns (uint[] memory amounts) {
amounts = CoinSwapLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'CSWP:34');
TransferHelper.safeTransferFrom(
path[0], msg.sender, CoinSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual ensure(deadline) returns (uint[] memory amounts) {
amounts = CoinSwapLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'CSWP:35');
TransferHelper.safeTransferFrom(
path[0], msg.sender, CoinSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'CSWP:36');
amounts = CoinSwapLibrary.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'CSWP:37');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(CoinSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
virtual
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'CSWP:38');
amounts = CoinSwapLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'CSWP:39');
TransferHelper.safeTransferFrom(
path[0], msg.sender, CoinSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'CSWP:40');
amounts = CoinSwapLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'CSWP:41');
TransferHelper.safeTransferFrom(
path[0], msg.sender, CoinSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
virtual
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'CSWP:42');
amounts = CoinSwapLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'CSWP:43');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(CoinSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
CoinSwapPair pair = CoinSwapPair(CoinSwapLibrary.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
{ // scope to avoid stack too deep errors
(uint reserveInput, uint reserveOutput, uint mulambda) = CoinSwapLibrary.getReservesAndmu(factory, input, output);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = CoinSwapLibrary.getAmountOut(amountInput, reserveInput, reserveOutput, mulambda);
}
(uint amount0Out, uint amount1Out) = input < output ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? CoinSwapLibrary.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(uint192(amount0Out<<96 | amount1Out), to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0], msg.sender, CoinSwapLibrary.pairFor(factory, path[0], path[1]), amountIn
);
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'CSWP:44'
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
payable
ensure(deadline)
{
require(path[0] == WETH, 'CSWP:45');
uint amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(CoinSwapLibrary.pairFor(factory, path[0], path[1]), amountIn));
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'CSWP:46'
);
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
ensure(deadline)
{
require(path[path.length - 1] == WETH, 'CSWP:47');
TransferHelper.safeTransferFrom(
path[0], msg.sender, CoinSwapLibrary.pairFor(factory, path[0], path[1]), amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint amountOut = IERC20(WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, 'CSWP:48');
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut, uint mulambda) public pure returns (uint amountOut) {
return CoinSwapLibrary.getAmountOut(amountIn, reserveIn, reserveOut, mulambda);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut, uint mulambda) public pure returns (uint amountIn) {
return CoinSwapLibrary.getAmountIn(amountOut, reserveIn, reserveOut, mulambda);
}
function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts) {
return CoinSwapLibrary.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path) public view returns (uint[] memory amounts) {
return CoinSwapLibrary.getAmountsIn(factory, amountOut, path);
}
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'CSWP70');
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'CSWP71');
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'CSWP72');
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'CSWP73');
}
}
library CoinSwapLibrary {
using SafeMath for uint;
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'08d6ace72c919d3777e7a6a0ae82941b79932ea4e7b37e16d8c04f7fd2783574'
))));
}
function getReservesAndmu(address factory, address tokenA, address tokenB) internal view returns
(uint reserveA, uint reserveB, uint mulambda) {
(uint224 reserve, uint224 circleData) = CoinSwapPair(pairFor(factory, tokenA, tokenB)).getReserves();
uint reserve0 = uint(reserve>>128);
uint reserve1 = uint(uint96(reserve>>32));
uint mulambda0 = uint(uint16(circleData >> 72))* uint56(circleData >> 160) * uint56(circleData);
uint mulambda1 = uint(uint16(circleData >> 56))* uint56(circleData >> 104) * uint56(circleData);
(reserveA, reserveB, mulambda) = tokenA < tokenB ?
(reserve0,reserve1, (mulambda0<<128) | mulambda1 ):(reserve1,reserve0, (mulambda1<<128) | mulambda0);
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut, uint mulambda) internal pure returns (uint amountOut) {
require((amountIn > 0) && (reserveOut > 0), 'CSWP:63');
uint mulambda0 = (mulambda>>128);
uint mulambda1 = uint(uint128(mulambda));
uint Z = 10**37-(mulambda0 * reserveIn * 1000);
uint R0=Z*Z;
Z= 10**37-(mulambda1 * reserveOut * 1000);
R0 += Z*Z;
uint ZZ = uint(10**37).sub(mulambda0 * (1000*reserveIn + amountIn * 997));
R0 = R0.sub(ZZ*ZZ);
R0 = SQRT.sqrt(R0);
amountOut = R0.sub(Z) / (mulambda1 * 1000);
if (amountOut > reserveOut) amountOut = reserveOut;
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut, uint mulambda) internal pure returns (uint amountIn) {
uint mulambda0 = (mulambda>>128);
uint mulambda1 = uint(uint128(mulambda));
uint Z= 10**37-(mulambda1 * reserveOut * 1000);
uint R1 = Z*Z;
Z = 10**37-(mulambda0 * reserveIn * 1000);
R1 += Z*Z;
uint ZZ = 10**37-(mulambda1 * 1000* (reserveOut.sub(amountOut)));
R1 =R1.sub(ZZ*ZZ);
amountIn = 1+ (Z.sub(SQRT.sqrt(R1))) / (mulambda0 * 997) ;
}
function getAmountsOut(address factory, uint amountIn, address[] memory path)
internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'CSWP:65');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut, uint mulambda)
= getReservesAndmu(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut, mulambda);
}
}
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'CSWP:66');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut, uint mulambda)
= getReservesAndmu(factory, path[i-1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut, mulambda);
}
}
}
library SQRT {
function sqrt(uint256 a) internal pure returns (uint256 x) {
if (a > 3) {
uint msbpos =0;
uint b=a;
if (b > 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {
msbpos += 128;
b = b >> 128;
}
if (b > 0xFFFFFFFFFFFFFFFF) {
msbpos += 64;
b = b>>64;
}
if (b > 0xFFFFFFFF ) {
msbpos += 32;
b = b>>32;
}
if (b > 0xFFFF ) {
msbpos += 16;
b = b>>16;
}
if (b > 0xFF ) {
msbpos += 8;
b = b>>8;
}
if (b > 0xF ) {
msbpos += 4;
}
msbpos += 4;
uint256 x0=a;
uint X=((a >> 1) + 1);
uint Y=2**(msbpos/2);
x = X< Y ? X : Y;
while (x < x0 ) {
x0 = x;
x = (a / x0 + x0) >> 1;
}
} else if (a != 0) {
x = 1;
}
}
}
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
|
update reserves and, on the first call per block, price accumulators
|
function _update(uint balance) private {
uint32 lastTime = uint32(balance);
uint32 deltaTime = uint32(block.timestamp) -lastTime ;
if (deltaTime>0 && lastTime>0) {
uint circle = circleData;
uint lambda0 = uint16(circle >> 72);
uint lambda1 = uint16(circle >> 56);
uint CmulambdaX = 10**34 - (balance>>128) *lambda0*uint56(circle)*uint56(circle >> 160);
uint CmulambdaY = 10**34 - uint96(balance>>32)*lambda1*uint56(circle)*uint56(circle >> 104);
priceCumulative += (((lambda0*CmulambdaX)<< 96)/(lambda1*CmulambdaY)) * deltaTime;
}
reserve = uint224(balance +deltaTime);
emit Sync(balance>>32);
}
| 6,170,208 |
./full_match/1/0xe0c5E70C879d1c170F64f66266651f4641f7c03d/sources/contracts/InsideOut.sol
|
Main minting function./
|
function mintIO() internal {
_totalSupply.increment();
uint256 tokenId = _totalSupply.current();
_safeMint(msg.sender, tokenId);
}
| 8,300,157 |
./full_match/1/0x646Df2Dc98741a0Ab5798DeAC6Fc62411dA41D96/sources/src/bridges/liquity/TroveBridge.sol
|
Redeem collateral. _tbAmount Amount of TB to burn. _interactionNonce Same as in convert(...) method. return collateral Amount of collateral withdrawn./
|
function _redeem(uint256 _tbAmount, uint256 _interactionNonce) private returns (uint256 collateral) {
if (!collateralClaimed) {
BORROWER_OPERATIONS.claimCollateral();
collateralClaimed = true;
}
collateral = (address(this).balance * _tbAmount) / totalSupply();
_burn(address(this), _tbAmount);
}
| 17,057,666 |
// File: contracts/vaults/IStrategy.sol
pragma solidity 0.5.17;
interface istrategy59 { //inject NONSTANDARD NAMING
function GETNAME35() external pure returns (string memory); //inject NONSTANDARD NAMING
function WANT31() external view returns (address); //inject NONSTANDARD NAMING
function WITHDRAW24(address) external; //inject NONSTANDARD NAMING
function WITHDRAW24(uint256) external; //inject NONSTANDARD NAMING
function WITHDRAWALL24() external returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF3() external view returns (uint256); //inject NONSTANDARD NAMING
}
// File: contracts/IERC20.sol
//SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.5.17;
interface ierc2080 { //inject NONSTANDARD NAMING
function TOTALSUPPLY74() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF3(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER92(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE58(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE17(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM23(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER57(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL94(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: contracts/ITreasury.sol
pragma solidity 0.5.17;
interface itreasury2 { //inject NONSTANDARD NAMING
function DEFAULTTOKEN28() external view returns (ierc2080); //inject NONSTANDARD NAMING
function DEPOSIT94(ierc2080 token, uint256 amount) external; //inject NONSTANDARD NAMING
function WITHDRAW24(uint256 amount, address withdrawAddress) external; //inject NONSTANDARD NAMING
}
// File: contracts/vaults/IVault.sol
pragma solidity 0.5.17;
interface ivault53 { //inject NONSTANDARD NAMING
function WANT31() external view returns (ierc2080); //inject NONSTANDARD NAMING
function TRANSFERFUNDSTOSTRATEGY94(address strategy, uint256 amount) external; //inject NONSTANDARD NAMING
function AVAILABLEFUNDS75() external view returns (uint256); //inject NONSTANDARD NAMING
}
// File: contracts/vaults/IVaultRewards.sol
pragma solidity 0.5.17;
interface ivaultrewards63 { //inject NONSTANDARD NAMING
function WANT31() external view returns (ierc2080); //inject NONSTANDARD NAMING
function NOTIFYREWARDAMOUNT2(uint256 reward) external; //inject NONSTANDARD NAMING
}
// File: contracts/vaults/IController.sol
pragma solidity 0.5.17;
interface icontroller20 { //inject NONSTANDARD NAMING
function CURRENTEPOCHTIME27() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF3(address) external view returns (uint256); //inject NONSTANDARD NAMING
function REWARDS0(address token) external view returns (ivaultrewards63); //inject NONSTANDARD NAMING
function VAULT69(address token) external view returns (ivault53); //inject NONSTANDARD NAMING
function ALLOWABLEAMOUNT15(address) external view returns (uint256); //inject NONSTANDARD NAMING
function TREASURY79() external view returns (itreasury2); //inject NONSTANDARD NAMING
function APPROVEDSTRATEGIES44(address, address) external view returns (bool); //inject NONSTANDARD NAMING
function GETHARVESTINFO14(address strategy, address user) //inject NONSTANDARD NAMING
external view returns (
uint256 vaultRewardPercentage,
uint256 hurdleAmount,
uint256 harvestPercentage
);
function WITHDRAW24(address, uint256) external; //inject NONSTANDARD NAMING
function EARN37(address, uint256) external; //inject NONSTANDARD NAMING
function INCREASEHURDLERATE27(address token) external; //inject NONSTANDARD NAMING
}
// File: contracts/ISwapRouter.sol
//SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.5.17;
interface swaprouter18 { //inject NONSTANDARD NAMING
function WETH90() external pure returns (address); //inject NONSTANDARD NAMING
function SWAPEXACTTOKENSFORTOKENS91( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
}
// File: contracts/SafeMath.sol
pragma solidity 0.5.17;
// Note: This file has been modified to include the sqrt function for quadratic voting
library math29 { //inject NONSTANDARD NAMING
function MAX82(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a >= b ? a : b;
}
function MIN43(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a < b ? a : b;
}
function AVERAGE17(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
function SQRT87(uint256 x) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 n = x / 2;
uint256 lstX = 0;
while (n != lstX){
lstX = n;
n = (n + x/n) / 2;
}
return uint256(n);
}
}
library safemath85 { //inject NONSTANDARD NAMING
function ADD14(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB75(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB75(a, b, "SafeMath: subtraction overflow");
}
function SUB75(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL41(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV62(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV62(a, b, "SafeMath: division by zero");
}
function DIV62(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD3(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD3(a, b, "SafeMath: modulo by zero");
}
function MOD3(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/zeppelin/Address.sol
pragma solidity 0.5.17;
library address35 { //inject NONSTANDARD NAMING
function ISCONTRACT42(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE96(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE71(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: contracts/zeppelin/SafeERC20.sol
pragma solidity 0.5.17;
library safeerc2099 { //inject NONSTANDARD NAMING
using safemath85 for uint256;
using address35 for address;
function SAFETRANSFER62(ierc2080 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.TRANSFER92.selector, to, value));
}
function SAFETRANSFERFROM40(ierc2080 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.TRANSFERFROM23.selector, from, to, value));
}
function SAFEAPPROVE5(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE58(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, value));
}
function SAFEINCREASEALLOWANCE71(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE58(address(this), spender).ADD14(value);
CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE44(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE58(address(this), spender).SUB75(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN65(ierc2080 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).ISCONTRACT42(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/vaults/strategy/MStableStrategy.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.5.17;
interface ibpt3 { //inject NONSTANDARD NAMING
function TOTALSUPPLY74() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF3(address whom) external view returns (uint); //inject NONSTANDARD NAMING
function GETSPOTPRICE26(address tokenIn, address tokenOut) external view returns (uint spotPrice); //inject NONSTANDARD NAMING
function SWAPEXACTAMOUNTIN69(address, uint, address, uint, uint) external returns (uint, uint); //inject NONSTANDARD NAMING
function SWAPEXACTAMOUNTOUT77(address, uint, address, uint, uint) external returns (uint, uint); //inject NONSTANDARD NAMING
function JOINSWAPEXTERNAMOUNTIN73( //inject NONSTANDARD NAMING
address tokenIn,
uint tokenAmountIn,
uint minPoolAmountOut
) external returns (uint poolAmountOut);
function EXITSWAPEXTERNAMOUNTOUT85( //inject NONSTANDARD NAMING
address tokenOut,
uint tokenAmountOut,
uint maxPoolAmountIn
) external returns (uint poolAmountIn);
function EXITSWAPPOOLAMOUNTIN6( //inject NONSTANDARD NAMING
address tokenOut,
uint poolAmountIn,
uint minAmountOut
) external returns (uint tokenAmountOut);
}
interface impool6 { //inject NONSTANDARD NAMING
function BALANCEOF3(address _account) external view returns (uint256); //inject NONSTANDARD NAMING
function EARNED23(address _account) external view returns (uint256, uint256); //inject NONSTANDARD NAMING
function STAKE12(uint256 _amount) external; //inject NONSTANDARD NAMING
function CLAIMREWARD81() external; //inject NONSTANDARD NAMING
function EXIT39() external; //inject NONSTANDARD NAMING
}
interface imtagov79 { //inject NONSTANDARD NAMING
function BALANCEOF3(address _account) external view returns (uint256); //inject NONSTANDARD NAMING
function EARNED23(address _account) external view returns (uint256); //inject NONSTANDARD NAMING
function CREATELOCK73(uint256 _value, uint256 _unlockTime) external; //inject NONSTANDARD NAMING
function WITHDRAW24() external; //inject NONSTANDARD NAMING
function INCREASELOCKAMOUNT91(uint256 _value) external; //inject NONSTANDARD NAMING
function CLAIMREWARD81() external; //inject NONSTANDARD NAMING
}
contract mstablestrat66 is istrategy59 { //inject NONSTANDARD NAMING
using safeerc2099 for ierc2080;
using address35 for address;
using safemath85 for uint256;
uint256 public constant performance_fee63 = 500; // 5% //inject NONSTANDARD NAMING
uint256 public constant denom43 = 10000; //inject NONSTANDARD NAMING
uint256 public hurdleLastUpdateTime;
uint256 public harvestAmountThisEpoch;
uint256 public strategistCollectedFee;
uint256 public numPools = 1;
ierc2080 internal usdc = ierc2080(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
ierc2080 internal musd = ierc2080(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5);
ierc2080 internal mta = ierc2080(0xa3BeD4E1c75D00fa6f4E5E6922DB7261B5E9AcD2);
ibpt3 internal musdcBpt = ibpt3(0x72Cd8f4504941Bf8c5a21d1Fd83A96499FD71d2C);
swaprouter18 public swapRouter = swaprouter18(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
impool6 internal mPool = impool6(0x881c72D1e6317f10a1cDCBe05040E7564E790C80);
imtagov79 internal mtaGov = imtagov79(0xaE8bC96DA4F9A9613c323478BE181FDb2Aa0E1BF);
ierc2080 public want = usdc; // should be set only in constructor or hardcoded
icontroller20 public controller; // should be set only in constructor
address public strategist; // mutable, but only by strategist
// want must be equal to an underlying vault token (Eg. USDC)
constructor(icontroller20 _controller) public {
controller = _controller;
strategist = msg.sender;
}
function GETNAME35() external pure returns (string memory) { //inject NONSTANDARD NAMING
return "MstableStrategy";
}
function SETSTRATEGIST71(address _strategist) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist, "!strategist");
strategist = _strategist;
}
function SETNUMPOOLSFORSWAP74(uint256 _numPools) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist, "!strategist");
numPools = _numPools;
}
function SETALLOWANCES18(ierc2080 token, address[] calldata recipients, bool isIncrease) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist, "!strategist");
for (uint i = 0; i < recipients.length; i++) {
require(
recipients[i] == address(musdcBpt) ||
recipients[i] == address(swapRouter) ||
recipients[i] == address(mPool) ||
recipients[i] == address(mtaGov),
"bad recipient"
);
uint256 allowance = isIncrease ? uint256(-1) : 0;
token.SAFEAPPROVE5(recipients[i], allowance);
}
}
// Assumed that caller checks against available funds in vault
function DEPOSIT94(uint256 amount) public { //inject NONSTANDARD NAMING
uint256 availFunds = controller.ALLOWABLEAMOUNT15(address(this));
require(amount <= availFunds, "exceed contAllowance");
controller.EARN37(address(this), amount);
// deposit into musdcBpt
uint256 bptTokenAmt = musdcBpt.JOINSWAPEXTERNAMOUNTIN73(address(want), amount, 0);
// deposit into mstable pool
mPool.STAKE12(bptTokenAmt);
// deposit any MTA token in this contract into mStaking contract
DEPOSITMTAINSTAKING28();
}
function BALANCEOF3() external view returns (uint256) { //inject NONSTANDARD NAMING
// get balance in mPool
uint256 bptStakeAmt = mPool.BALANCEOF3(address(this));
// get usdc + musd amts in BPT, and total BPT
uint256 usdcAmt = usdc.BALANCEOF3(address(musdcBpt));
uint256 musdAmt = musd.BALANCEOF3(address(musdcBpt));
uint256 totalBptAmt = musdcBpt.TOTALSUPPLY74();
// convert musd to usdc
usdcAmt = usdcAmt.ADD14(
musdAmt.MUL41(1e18).DIV62(musdcBpt.GETSPOTPRICE26(address(musd), address(usdc)))
);
return bptStakeAmt.MUL41(usdcAmt).DIV62(totalBptAmt);
}
function EARNED23() external view returns (uint256) { //inject NONSTANDARD NAMING
(uint256 earnedAmt,) = mPool.EARNED23(address(this));
return earnedAmt.ADD14(mtaGov.EARNED23(address(this)));
}
function WITHDRAW24(address token) external { //inject NONSTANDARD NAMING
ierc2080 erc20Token = ierc2080(token);
require(msg.sender == address(controller), "!controller");
erc20Token.SAFETRANSFER62(address(controller), erc20Token.BALANCEOF3(address(this)));
}
function WITHDRAW24(uint256 amount) external { //inject NONSTANDARD NAMING
require(msg.sender == address(controller), "!controller");
// exit fully
mPool.EXIT39();
// convert to desired amount
musdcBpt.EXITSWAPEXTERNAMOUNTOUT85(address(want), amount, uint256(-1));
// deposit whatever remaining bpt back into mPool
mPool.STAKE12(musdcBpt.BALANCEOF3(address(this)));
// send funds to vault
want.SAFETRANSFER62(address(controller.VAULT69(address(want))), amount);
}
function WITHDRAWALL24() external returns (uint256 balance) { //inject NONSTANDARD NAMING
require(msg.sender == address(controller), "!controller");
// exit fully
mPool.EXIT39();
// convert reward to want tokens
// in case swap fails, continue
(bool success, ) = address(this).call(
abi.encodeWithSignature(
"exchangeRewardForWant(bool)",
true
)
);
// to remove compiler warning
success;
// convert bpt to want tokens
musdcBpt.EXITSWAPPOOLAMOUNTIN6(
address(want),
musdcBpt.BALANCEOF3(address(this)),
0
);
// exclude collected strategist fee
balance = want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee);
// send funds to vault
want.SAFETRANSFER62(address(controller.VAULT69(address(want))), balance);
}
function HARVEST87(bool claimMPool, bool claimGov) external { //inject NONSTANDARD NAMING
if (claimMPool) mPool.CLAIMREWARD81();
if (claimGov) mtaGov.CLAIMREWARD81();
// convert 80% reward to want tokens
// in case swap fails, return
(bool success, ) = address(this).call(
abi.encodeWithSignature(
"exchangeRewardForWant(bool)",
false
)
);
// to remove compiler warning
if (!success) return;
uint256 amount = want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee);
uint256 vaultRewardPercentage;
uint256 hurdleAmount;
uint256 harvestPercentage;
uint256 epochTime;
(vaultRewardPercentage, hurdleAmount, harvestPercentage) =
controller.GETHARVESTINFO14(address(this), msg.sender);
// check if harvest amount has to be reset
if (hurdleLastUpdateTime < epochTime) {
// reset collected amount
harvestAmountThisEpoch = 0;
}
// update variables
hurdleLastUpdateTime = block.timestamp;
harvestAmountThisEpoch = harvestAmountThisEpoch.ADD14(amount);
// first, take harvester fee
uint256 harvestFee = amount.MUL41(harvestPercentage).DIV62(denom43);
want.SAFETRANSFER62(msg.sender, harvestFee);
uint256 fee;
// then, if hurdle amount has been exceeded, take performance fee
if (harvestAmountThisEpoch >= hurdleAmount) {
fee = amount.MUL41(performance_fee63).DIV62(denom43);
strategistCollectedFee = strategistCollectedFee.ADD14(fee);
}
// do the subtraction of harvester and strategist fees
amount = amount.SUB75(harvestFee).SUB75(fee);
// calculate how much is to be re-invested
// fee = vault reward amount, reusing variable
fee = amount.MUL41(vaultRewardPercentage).DIV62(denom43);
want.SAFETRANSFER62(address(controller.REWARDS0(address(want))), fee);
controller.REWARDS0(address(want)).NOTIFYREWARDAMOUNT2(fee);
amount = amount.SUB75(fee);
// finally, use remaining want amount for reinvestment
amount = musdcBpt.JOINSWAPEXTERNAMOUNTIN73(address(want), amount, 0);
// deposit into mstable pool
mPool.STAKE12(amount);
// deposit any MTA token in this contract into mStaking contract
DEPOSITMTAINSTAKING28();
}
function WITHDRAWSTRATEGISTFEE97() external { //inject NONSTANDARD NAMING
strategistCollectedFee = 0;
want.SAFETRANSFER62(strategist, strategistCollectedFee);
}
function EXITMGOV72() external { //inject NONSTANDARD NAMING
mtaGov.WITHDRAW24();
// convert to want tokens
// in case swap fails, continue
(bool success, ) = address(this).call(
abi.encodeWithSignature(
"exchangeRewardForWant(bool)",
true
)
);
// to remove compiler warning
success;
want.SAFETRANSFER62(
address(controller.REWARDS0(address(want))),
want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee)
);
}
function EXCHANGEREWARDFORWANT67(bool exchangeAll) public { //inject NONSTANDARD NAMING
uint256 swapAmt = mta.BALANCEOF3(address(this));
if (swapAmt == 0) return;
// do the exchange
address[] memory routeDetails = new address[](3);
routeDetails[0] = address(mta);
routeDetails[1] = swapRouter.WETH90();
routeDetails[2] = address(want);
swapRouter.SWAPEXACTTOKENSFORTOKENS91(
exchangeAll ? swapAmt : swapAmt.MUL41(8000).DIV62(denom43),
0,
routeDetails,
address(this),
block.timestamp + 100
);
}
function DEPOSITMTAINSTAKING28() internal { //inject NONSTANDARD NAMING
uint256 mtaBal = mta.BALANCEOF3(address(this));
if (mtaBal == 0) return;
if (mtaGov.BALANCEOF3(address(this)) == 0) {
// create lock with max time
mtaGov.CREATELOCK73(mtaBal, 1632580257);
} else {
// increase amount
mtaGov.INCREASELOCKAMOUNT91(mtaBal);
}
}
}
|
inject NONSTANDARD NAMING
|
function VAULT69(address token) external view returns (ivault53);
| 1,825,062 |
// Based on https://github.com/HausDAO/MinionSummoner/blob/main/MinionFactory.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
pragma abicoder v2;
import "@gnosis.pm/safe-contracts/contracts/GnosisSafe.sol";
import "@gnosis.pm/safe-contracts/contracts/libraries/MultiSend.sol";
import "./zodiac/core/Module.sol";
import "./zodiac/factory/ModuleProxyFactory.sol";
interface IERC20 {
// brief interface for moloch erc20 token txs
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
}
interface IMOLOCH {
// brief interface for moloch dao v2
function depositToken() external view returns (address);
function tokenWhitelist(address token) external view returns (bool);
function totalShares() external view returns (uint256);
function getProposalFlags(uint256 proposalId)
external
view
returns (bool[6] memory);
function getUserTokenBalance(address user, address token)
external
view
returns (uint256);
function members(address user)
external
view
returns (
address,
uint256,
uint256,
bool,
uint256,
uint256
);
function memberAddressByDelegateKey(address user)
external
view
returns (address);
function userTokenBalances(address user, address token)
external
view
returns (uint256);
function cancelProposal(uint256 proposalId) external;
function submitProposal(
address applicant,
uint256 sharesRequested,
uint256 lootRequested,
uint256 tributeOffered,
address tributeToken,
uint256 paymentRequested,
address paymentToken,
string calldata details
) external returns (uint256);
function withdrawBalance(address token, uint256 amount) external;
struct Proposal {
address applicant; // the applicant who wishes to become a member - this key will be used for withdrawals (doubles as guild kick target for gkick proposals)
address proposer; // the account that submitted the proposal (can be non-member)
address sponsor; // the member that sponsored the proposal (moving it into the queue)
uint256 sharesRequested; // the # of shares the applicant is requesting
uint256 lootRequested; // the amount of loot the applicant is requesting
uint256 tributeOffered; // amount of tokens offered as tribute
address tributeToken; // tribute token contract reference
uint256 paymentRequested; // amount of tokens requested as payment
address paymentToken; // payment token contract reference
uint256 startingPeriod; // the period in which voting can start for this proposal
uint256 yesVotes; // the total number of YES votes for this proposal
uint256 noVotes; // the total number of NO votes for this proposal
bool[6] flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick]
string details; // proposal details - could be IPFS hash, plaintext, or JSON
uint256 maxTotalSharesAndLootAtYesVote; // the maximum # of total shares encountered at a yes vote on this proposal
}
function proposals(uint256 proposalId)
external
view
returns (
address,
address,
address,
uint256,
uint256,
uint256,
address,
uint256,
address,
uint256,
uint256,
uint256
);
}
/// @title SafeMinion - Gnosis compatible module to manage state of a Safe through Moloch v2 governance
/// @dev Executes arbitrary transactions on behalf of the Safe based on proposals submitted through this Minion's interface
/// Must be configured to interact with one Moloch contract and one Safe
///
/// Safe Settings:
///
/// Must be enabled on the Safe through `enableModule`
/// This happens automatically if using the included minion & safe factory
/// Optionally can be enabled as an owner on the Safe so the Moloch can act as a signer
/// Optionally can enable additional signers on the Safe to act as delegates to bypass governance
///
/// Minion Settings:
///
/// Optional Quorum settings for early execution of proposals
///
/// Actions:
///
/// All actions use the Gnosis multisend library and must be encoded as shown in docs/ tests
///
/// Minion is owned by the Safe
/// Owner can change the safe address via `setAvatar`
/// @author Isaac Patka, Dekan Brown
contract SafeMinion is Enum, Module {
// Moloch configured to instruct this minion
IMOLOCH public moloch;
// Gnosis multisendLibrary library contract
address public multisendLibrary;
// Default ERC20 token address to include in Moloch proposals as tribute token
address public molochDepositToken;
// Optional quorum for early execution - set to 0 to disable
uint256 public minQuorum;
// Keep track of actions associated with proposal IDs
struct Action {
bytes32 id;
address proposer;
bool executed;
address token;
uint256 amount;
address moloch;
bool memberOnlyEnabled; // 0 anyone , 1 memberOnly
}
mapping(uint256 => Action) public actions;
// Error Strings
string private constant ERROR_REQS_NOT_MET =
"Minion::proposal execution requirements not met";
string private constant ERROR_NOT_VALID = "Minion::not a valid operation";
string private constant ERROR_EXECUTED = "Minion::action already executed";
string private constant ERROR_DELETED = "Minion::action was deleted";
string private constant ERROR_CALL_FAIL = "Minion::call failure";
string private constant ERROR_NOT_PROPOSER = "Minion::not proposer";
string private constant ERROR_MEMBER_ONLY = "Minion::not member";
string private constant ERROR_AVATAR_ONLY = "Minion::not avatar";
string private constant ERROR_NOT_SPONSORED =
"Minion::proposal not sponsored";
string private constant ERROR_MIN_QUORUM_BOUNDS =
"Minion::minQuorum must be 0 to 100";
string private constant ERROR_ZERO_DEPOSIT_TOKEN =
"Minion:zero deposit token is not allowed";
string private constant ERROR_NO_ACTION = "Minion:action does not exist";
string private constant ERROR_NOT_WL = "Minion:token is not whitelisted";
event ProposeNewAction(
bytes32 indexed id,
uint256 indexed proposalId,
address withdrawToken,
uint256 withdrawAmount,
address moloch,
bool memberOnly,
bytes transactions
);
event ExecuteAction(
bytes32 indexed id,
uint256 indexed proposalId,
bytes transactions,
address avatar
);
event DoWithdraw(address token, uint256 amount);
event ActionCanceled(uint256 proposalId);
event ActionDeleted(uint256 proposalId);
event CrossWithdraw(address target, address token, uint256 amount);
modifier memberOnly() {
require(isMember(msg.sender), ERROR_MEMBER_ONLY);
_;
}
modifier avatarOnly() {
require(msg.sender == avatar, ERROR_AVATAR_ONLY);
_;
}
/// @dev This constructor ensures that this contract can only be used as a master copy for Proxy contracts
constructor() {
// By setting the owner it is not possible to call setUp
// This is an unusable minion, perfect for the singleton
__Ownable_init();
transferOwnership(address(0xdead));
}
/// @dev Factory Friendly setup function
/// @notice Can only be called once by factory
/// @param _initializationParams ABI Encoded parameters needed for configuration
function setUp(bytes memory _initializationParams) public override {
// Decode initialization parameters
(
address _moloch,
address _avatar,
address _multisendLibrary,
uint256 _minQuorum
) = abi.decode(
_initializationParams,
(address, address, address, uint256)
);
// Initialize ownership and transfer immediately to avatar
// Ownable Init reverts if already initialized
__Ownable_init();
transferOwnership(_avatar);
// min quorum must be between 0% and 100%, if 0 early execution is disabled
require(_minQuorum >= 0 && _minQuorum <= 100, ERROR_MIN_QUORUM_BOUNDS);
minQuorum = _minQuorum;
// Set the moloch to instruct this minion
moloch = IMOLOCH(_moloch);
// Set the Gnosis safe address
avatar = _avatar;
// Set the library to use for all transaction executions
multisendLibrary = _multisendLibrary;
// Set the default moloch token to use in proposals
molochDepositToken = moloch.depositToken();
// Set as initialized so setUp cannot be entered again
initialized = true;
}
/// @dev Member accessible interface to withdraw funds from Moloch directly to Safe
/// @notice Can only be called by member of Moloch
/// @param _token ERC20 address of token to withdraw
/// @param _amount ERC20 token amount to withdraw
function doWithdraw(address _token, uint256 _amount) public memberOnly {
// Construct transaction data for safe to execute
bytes memory withdrawData = abi.encodeWithSelector(
moloch.withdrawBalance.selector,
_token,
_amount
);
require(
exec(address(moloch), 0, withdrawData, Operation.Call),
ERROR_CALL_FAIL
);
emit DoWithdraw(_token, _amount);
}
/// @dev Member accessible interface to withdraw funds from another Moloch directly to Safe or to the DAO
/// @notice Can only be called by member of Moloch
/// @param _target MOLOCH address to withdraw from
/// @param _token ERC20 address of token to withdraw
/// @param _amount ERC20 token amount to withdraw
function crossWithdraw(address _target, address _token, uint256 _amount, bool _transfer) external memberOnly {
// Construct transaction data for safe to execute
bytes memory withdrawData = abi.encodeWithSelector(
IMOLOCH(_target).withdrawBalance.selector,
_token,
_amount
);
require(
exec(_target, 0, withdrawData, Operation.Call),
ERROR_CALL_FAIL
);
// Transfers token into DAO.
if(_transfer) {
bool whitelisted = moloch.tokenWhitelist(_token);
require(whitelisted, ERROR_NOT_WL);
bytes memory transferData = abi.encodeWithSelector(
IERC20(_token).transfer.selector,
address(moloch),
_amount
);
require(
exec(_token, 0, transferData, Operation.Call),
ERROR_CALL_FAIL
);
}
emit CrossWithdraw(_target, _token, _amount);
}
/// @dev Internal utility function to store hash of transaction data to ensure executed action is the same as proposed action
/// @param _proposalId Proposal ID associated with action to delete
/// @param _transactions Multisend encoded transactions to be executed if proposal succeeds
/// @param _withdrawToken ERC20 token for any payment requested
/// @param _withdrawAmount ERC20 amount for any payment requested
/// @param _memberOnlyEnabled Optionally restrict execution of this action to only memgbers
function saveAction(
uint256 _proposalId,
bytes memory _transactions,
address _withdrawToken,
uint256 _withdrawAmount,
bool _memberOnlyEnabled
) internal {
bytes32 _id = hashOperation(_transactions);
Action memory _action = Action({
id: _id,
proposer: msg.sender,
executed: false,
token: _withdrawToken,
amount: _withdrawAmount,
moloch: address(moloch),
memberOnlyEnabled: _memberOnlyEnabled
});
actions[_proposalId] = _action;
emit ProposeNewAction(
_id,
_proposalId,
_withdrawToken,
_withdrawAmount,
address(moloch),
_memberOnlyEnabled,
_transactions
);
}
/// @dev Utility function to check if proposal is passed internally and can also be used on the DAO UI
/// @param _proposalId Proposal ID associated with action to check
function isPassed(uint256 _proposalId) public view returns (bool) {
// Retrieve proposal status flags from moloch
bool[6] memory flags = moloch.getProposalFlags(_proposalId);
require(flags[0], ERROR_NOT_SPONSORED);
// If proposal has passed, return without checking quorm
if (flags[2]) return true;
// If quorum enabled, calculate status. Quorum must be met and there cannot be any NO votes
if (minQuorum != 0) {
uint256 totalShares = moloch.totalShares();
(, , , , , , , , , , uint256 yesVotes, uint256 noVotes) = moloch
.proposals(_proposalId);
uint256 quorum = (yesVotes * 100) / totalShares;
return quorum >= minQuorum && noVotes < 1;
}
return false;
}
/// @dev Internal utility function to check if user is member of associate Moloch
/// @param _user Address of user to check
function isMember(address _user) internal view returns (bool) {
// member only check should check if member or delegate
address _memberAddress = moloch.memberAddressByDelegateKey(_user);
(, uint256 _shares, , , , ) = moloch.members(_memberAddress);
return _shares > 0;
}
/// @dev Internal utility function to hash transactions for storing & checking prior to execution
/// @param _transactions Encoded transction data
function hashOperation(bytes memory _transactions)
public
pure
virtual
returns (bytes32 hash)
{
return keccak256(abi.encode(_transactions));
}
/// @dev Member accessible interface to make a proposal to Moloch and store associated action information
/// @notice Can only be called by member of Moloch
/// @param _transactions Multisend encoded transactions to be executed if proposal succeeds
/// @param _withdrawToken ERC20 token for any payment requested
/// @param _withdrawAmount ERC20 amount for any payment requested
/// @param _details Optional metadata to include in proposal
/// @param _memberOnlyEnabled Optionally restrict execution of this action to only memgbers
function proposeAction(
bytes memory _transactions,
address _withdrawToken,
uint256 _withdrawAmount,
string calldata _details,
bool _memberOnlyEnabled
) external memberOnly returns (uint256) {
uint256 _proposalId = moloch.submitProposal(
avatar,
0,
0,
0,
molochDepositToken,
_withdrawAmount,
_withdrawToken,
_details
);
saveAction(
_proposalId,
_transactions,
_withdrawToken,
_withdrawAmount,
_memberOnlyEnabled
);
return _proposalId;
}
/// @dev Function to delete an action submitted in prior proposal
/// @notice Can only be called by the avatar which means this can only be called if passed by another
/// proposal or by a delegated signer on the Safe
/// Makes it so the action can not be executed
/// @param _proposalId Proposal ID associated with action to delete
function deleteAction(uint256 _proposalId)
external
avatarOnly
returns (bool)
{
// check action exists
require(actions[_proposalId].proposer != address(0), ERROR_NO_ACTION);
delete actions[_proposalId];
emit ActionDeleted(_proposalId);
return true;
}
/// @dev Function to Execute arbitrary code as the minion - useful if funds are accidentally sent here
/// @notice Can only be called by the avatar which means this can only be called if passed by another
/// proposal or by a delegated signer on the Safe
/// @param _to address to call
/// @param _value value to include in wei
/// @param _data arbitrary transaction data
function executeAsMinion(address _to, uint256 _value, bytes calldata _data) external avatarOnly {
(bool success,) = _to.call{value: _value}(_data);
require(success, "call failure");
}
/// @dev Function to execute an action if the proposal has passed or quorum has been met
/// Can be restricted to only members if specified in proposal
/// @param _proposalId Proposal ID associated with action to execute
/// @param _transactions Multisend encoded transactions, must be same as transactions in proposal
function executeAction(uint256 _proposalId, bytes memory _transactions)
external
returns (bool)
{
Action memory _action = actions[_proposalId];
require(!_action.executed, ERROR_EXECUTED);
// Mark executed before doing any external stuff
actions[_proposalId].executed = true;
// Check if restricted to only member execution and enforce it
if (_action.memberOnlyEnabled) {
require(isMember(msg.sender), ERROR_MEMBER_ONLY);
}
// Confirm proposal has passed or quorum is met
require(isPassed(_proposalId), ERROR_REQS_NOT_MET);
// Confirm action has not been deleted prior to attempting execution
require(_action.id != 0, ERROR_DELETED);
// Recover the hash of the submitted transctions and confirm they match the proposal
bytes32 _id = hashOperation(_transactions);
require(_id == _action.id, ERROR_NOT_VALID);
// Withdraw tokens from Moloch to safe if specified by the proposal, and if they have not already been withdrawn via `doWithdraw`
if (
_action.amount > 0 &&
moloch.getUserTokenBalance(avatar, _action.token) > 0
) {
// withdraw tokens if any
doWithdraw(
_action.token,
moloch.getUserTokenBalance(avatar, _action.token)
);
}
// Execute the action via the multisend library
require(
exec(multisendLibrary, 0, _transactions, Operation.DelegateCall),
ERROR_CALL_FAIL
);
emit ExecuteAction(_id, _proposalId, _transactions, msg.sender);
delete actions[_proposalId];
return true;
}
/// @dev Function to cancel an action by the proposer if not yet sponsored
/// @param _proposalId Proposal ID associated with action to cancel
function cancelAction(uint256 _proposalId) external {
Action memory action = actions[_proposalId];
require(msg.sender == action.proposer, ERROR_NOT_PROPOSER);
delete actions[_proposalId];
moloch.cancelProposal(_proposalId);
emit ActionCanceled(_proposalId);
}
}
/// @title SafeMinionSummoner - Factory contract to depoy new Minions and Safes
/// @dev Can deploy a minion and a new safe, or just a minion to be attached to an existing safe
/// @author Isaac Patka, Dekan Brown
contract SafeMinionSummoner is ModuleProxyFactory {
// Template contract to use for new minion proxies
address payable public immutable safeMinionSingleton;
// Template contract to use for new Gnosis safe proxies
address public gnosisSingleton;
// Library to use for EIP1271 compatability
address public gnosisFallbackLibrary;
// Library to use for all safe transaction executions
address public gnosisMultisendLibrary;
// Track list and count of deployed minions
address[] public minionList;
uint256 public minionCount;
// Track metadata and associated moloch for deployed minions
struct AMinion {
address moloch;
string details;
}
mapping(address => AMinion) public minions;
// Public type data
string public constant minionType = "SAFE MINION V0";
event SummonMinion(
address indexed minion,
address indexed moloch,
address indexed avatar,
string details,
string minionType,
uint256 minQuorum
);
/// @dev Construtor sets the initial templates
/// @notice Can only be called once by factory
/// @param _safeMinionSingleton Template contract to be used for minion factory
/// @param _gnosisSingleton Template contract to be used for safe factory
/// @param _gnosisFallbackLibrary Library contract to be used in configuring new safes
/// @param _gnosisMultisendLibrary Library contract to be used in configuring new safes
constructor(
address payable _safeMinionSingleton,
address _gnosisSingleton,
address _gnosisFallbackLibrary,
address _gnosisMultisendLibrary
) {
safeMinionSingleton = _safeMinionSingleton;
gnosisSingleton = _gnosisSingleton;
gnosisFallbackLibrary = _gnosisFallbackLibrary;
gnosisMultisendLibrary = _gnosisMultisendLibrary;
}
/// @dev Function to only summon a minion to be attached to an existing safe
/// @param _moloch Already deployed Moloch to instruct minion
/// @param _avatar Already deployed safe
/// @param _details Optional metadata to store
/// @param _minQuorum Optional quorum settings, set 0 to disable
/// @param _saltNonce Number used to calculate the address of the new minion
function summonMinion(
address _moloch,
address _avatar,
string memory _details,
uint256 _minQuorum,
uint256 _saltNonce
) external returns (address) {
// Encode initializer for setup function
bytes memory _initializer = abi.encode(
_moloch,
_avatar,
gnosisMultisendLibrary,
_minQuorum
);
bytes memory _initializerCall = abi.encodeWithSignature(
"setUp(bytes)",
_initializer
);
SafeMinion _minion = SafeMinion(
payable(
deployModule(safeMinionSingleton, _initializerCall, _saltNonce)
)
);
minions[address(_minion)] = AMinion(_moloch, _details);
minionList.push(address(_minion));
minionCount++;
emit SummonMinion(
address(_minion),
_moloch,
_avatar,
_details,
minionType,
_minQuorum
);
return (address(_minion));
}
/// @dev Function to summon minion and configure with a new safe
/// @param _moloch Already deployed Moloch to instruct minion
/// @param _details Optional metadata to store
/// @param _minQuorum Optional quorum settings, set 0 to disable
/// @param _saltNonce Number used to calculate the address of the new minion
function summonMinionAndSafe(
address _moloch,
string memory _details,
uint256 _minQuorum,
uint256 _saltNonce
) external returns (address) {
// Deploy new minion but do not set it up yet
SafeMinion _minion = SafeMinion(
payable(createProxy(safeMinionSingleton, keccak256(abi.encodePacked(_moloch, _saltNonce))))
);
// Deploy new safe but do not set it up yet
GnosisSafe _safe = GnosisSafe(payable(createProxy(gnosisSingleton, keccak256(abi.encodePacked(address(_minion), _saltNonce)))));
// Initialize the minion now that we have the new safe address
_minion.setUp(
abi.encode(_moloch, address(_safe), gnosisMultisendLibrary, _minQuorum)
);
// Generate delegate calls so the safe calls enableModule on itself during setup
bytes memory _enableMinion = abi.encodeWithSignature(
"enableModule(address)",
address(_minion)
);
bytes memory _enableMinionMultisend = abi.encodePacked(
uint8(0),
address(_safe),
uint256(0),
uint256(_enableMinion.length),
bytes(_enableMinion)
);
bytes memory _multisendAction = abi.encodeWithSignature(
"multiSend(bytes)",
_enableMinionMultisend
);
// Workaround for solidity dynamic memory array
address[] memory _owners = new address[](1);
_owners[0] = address(_minion);
// Call setup on safe to enable our new module and set the module as the only signer
_safe.setup(
_owners,
1,
gnosisMultisendLibrary,
_multisendAction,
gnosisFallbackLibrary,
address(0),
0,
payable(address(0))
);
minions[address(_minion)] = AMinion(_moloch, _details);
minionList.push(address(_minion));
minionCount++;
emit SummonMinion(
address(_minion),
_moloch,
address(_safe),
_details,
minionType,
_minQuorum
);
return (address(_minion));
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "./base/ModuleManager.sol";
import "./base/OwnerManager.sol";
import "./base/FallbackManager.sol";
import "./base/GuardManager.sol";
import "./common/EtherPaymentFallback.sol";
import "./common/Singleton.sol";
import "./common/SignatureDecoder.sol";
import "./common/SecuredTokenTransfer.sol";
import "./common/StorageAccessible.sol";
import "./interfaces/ISignatureValidator.sol";
import "./external/GnosisSafeMath.sol";
/// @title Gnosis Safe - A multisignature wallet with support for confirmations using signed messages based on ERC191.
/// @author Stefan George - <[email protected]>
/// @author Richard Meissner - <[email protected]>
contract GnosisSafe is
EtherPaymentFallback,
Singleton,
ModuleManager,
OwnerManager,
SignatureDecoder,
SecuredTokenTransfer,
ISignatureValidatorConstants,
FallbackManager,
StorageAccessible,
GuardManager
{
using GnosisSafeMath for uint256;
string public constant VERSION = "1.3.0";
// keccak256(
// "EIP712Domain(uint256 chainId,address verifyingContract)"
// );
bytes32 private constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218;
// keccak256(
// "SafeTx(address to,uint256 value,bytes data,uint8 operation,uint256 safeTxGas,uint256 baseGas,uint256 gasPrice,address gasToken,address refundReceiver,uint256 nonce)"
// );
bytes32 private constant SAFE_TX_TYPEHASH = 0xbb8310d486368db6bd6f849402fdd73ad53d316b5a4b2644ad6efe0f941286d8;
event SafeSetup(address indexed initiator, address[] owners, uint256 threshold, address initializer, address fallbackHandler);
event ApproveHash(bytes32 indexed approvedHash, address indexed owner);
event SignMsg(bytes32 indexed msgHash);
event ExecutionFailure(bytes32 txHash, uint256 payment);
event ExecutionSuccess(bytes32 txHash, uint256 payment);
uint256 public nonce;
bytes32 private _deprecatedDomainSeparator;
// Mapping to keep track of all message hashes that have been approve by ALL REQUIRED owners
mapping(bytes32 => uint256) public signedMessages;
// Mapping to keep track of all hashes (message or transaction) that have been approve by ANY owners
mapping(address => mapping(bytes32 => uint256)) public approvedHashes;
// This constructor ensures that this contract can only be used as a master copy for Proxy contracts
constructor() {
// By setting the threshold it is not possible to call setup anymore,
// so we create a Safe with 0 owners and threshold 1.
// This is an unusable Safe, perfect for the singleton
threshold = 1;
}
/// @dev Setup function sets initial storage of contract.
/// @param _owners List of Safe owners.
/// @param _threshold Number of required confirmations for a Safe transaction.
/// @param to Contract address for optional delegate call.
/// @param data Data payload for optional delegate call.
/// @param fallbackHandler Handler for fallback calls to this contract
/// @param paymentToken Token that should be used for the payment (0 is ETH)
/// @param payment Value that should be paid
/// @param paymentReceiver Adddress that should receive the payment (or 0 if tx.origin)
function setup(
address[] calldata _owners,
uint256 _threshold,
address to,
bytes calldata data,
address fallbackHandler,
address paymentToken,
uint256 payment,
address payable paymentReceiver
) external {
// setupOwners checks if the Threshold is already set, therefore preventing that this method is called twice
setupOwners(_owners, _threshold);
if (fallbackHandler != address(0)) internalSetFallbackHandler(fallbackHandler);
// As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules
setupModules(to, data);
if (payment > 0) {
// To avoid running into issues with EIP-170 we reuse the handlePayment function (to avoid adjusting code of that has been verified we do not adjust the method itself)
// baseGas = 0, gasPrice = 1 and gas = payment => amount = (payment + 0) * 1 = payment
handlePayment(payment, 0, 1, paymentToken, paymentReceiver);
}
emit SafeSetup(msg.sender, _owners, _threshold, to, fallbackHandler);
}
/// @dev Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction.
/// Note: The fees are always transferred, even if the user transaction fails.
/// @param to Destination address of Safe transaction.
/// @param value Ether value of Safe transaction.
/// @param data Data payload of Safe transaction.
/// @param operation Operation type of Safe transaction.
/// @param safeTxGas Gas that should be used for the Safe transaction.
/// @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
/// @param gasPrice Gas price that should be used for the payment calculation.
/// @param gasToken Token address (or 0 if ETH) that is used for the payment.
/// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
/// @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v})
function execTransaction(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver,
bytes memory signatures
) public payable virtual returns (bool success) {
bytes32 txHash;
// Use scope here to limit variable lifetime and prevent `stack too deep` errors
{
bytes memory txHashData =
encodeTransactionData(
// Transaction info
to,
value,
data,
operation,
safeTxGas,
// Payment info
baseGas,
gasPrice,
gasToken,
refundReceiver,
// Signature info
nonce
);
// Increase nonce and execute transaction.
nonce++;
txHash = keccak256(txHashData);
checkSignatures(txHash, txHashData, signatures);
}
address guard = getGuard();
{
if (guard != address(0)) {
Guard(guard).checkTransaction(
// Transaction info
to,
value,
data,
operation,
safeTxGas,
// Payment info
baseGas,
gasPrice,
gasToken,
refundReceiver,
// Signature info
signatures,
msg.sender
);
}
}
// We require some gas to emit the events (at least 2500) after the execution and some to perform code until the execution (500)
// We also include the 1/64 in the check that is not send along with a call to counteract potential shortings because of EIP-150
require(gasleft() >= ((safeTxGas * 64) / 63).max(safeTxGas + 2500) + 500, "GS010");
// Use scope here to limit variable lifetime and prevent `stack too deep` errors
{
uint256 gasUsed = gasleft();
// If the gasPrice is 0 we assume that nearly all available gas can be used (it is always more than safeTxGas)
// We only substract 2500 (compared to the 3000 before) to ensure that the amount passed is still higher than safeTxGas
success = execute(to, value, data, operation, gasPrice == 0 ? (gasleft() - 2500) : safeTxGas);
gasUsed = gasUsed.sub(gasleft());
// If no safeTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful
// This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert
require(success || safeTxGas != 0 || gasPrice != 0, "GS013");
// We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls
uint256 payment = 0;
if (gasPrice > 0) {
payment = handlePayment(gasUsed, baseGas, gasPrice, gasToken, refundReceiver);
}
if (success) emit ExecutionSuccess(txHash, payment);
else emit ExecutionFailure(txHash, payment);
}
{
if (guard != address(0)) {
Guard(guard).checkAfterExecution(txHash, success);
}
}
}
function handlePayment(
uint256 gasUsed,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver
) private returns (uint256 payment) {
// solhint-disable-next-line avoid-tx-origin
address payable receiver = refundReceiver == address(0) ? payable(tx.origin) : refundReceiver;
if (gasToken == address(0)) {
// For ETH we will only adjust the gas price to not be higher than the actual used gas price
payment = gasUsed.add(baseGas).mul(gasPrice < tx.gasprice ? gasPrice : tx.gasprice);
require(receiver.send(payment), "GS011");
} else {
payment = gasUsed.add(baseGas).mul(gasPrice);
require(transferToken(gasToken, receiver, payment), "GS012");
}
}
/**
* @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.
* @param dataHash Hash of the data (could be either a message hash or transaction hash)
* @param data That should be signed (this is passed to an external validator contract)
* @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.
*/
function checkSignatures(
bytes32 dataHash,
bytes memory data,
bytes memory signatures
) public view {
// Load threshold to avoid multiple storage loads
uint256 _threshold = threshold;
// Check that a threshold is set
require(_threshold > 0, "GS001");
checkNSignatures(dataHash, data, signatures, _threshold);
}
/**
* @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.
* @param dataHash Hash of the data (could be either a message hash or transaction hash)
* @param data That should be signed (this is passed to an external validator contract)
* @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.
* @param requiredSignatures Amount of required valid signatures.
*/
function checkNSignatures(
bytes32 dataHash,
bytes memory data,
bytes memory signatures,
uint256 requiredSignatures
) public view {
// Check that the provided signature data is not too short
require(signatures.length >= requiredSignatures.mul(65), "GS020");
// There cannot be an owner with address 0.
address lastOwner = address(0);
address currentOwner;
uint8 v;
bytes32 r;
bytes32 s;
uint256 i;
for (i = 0; i < requiredSignatures; i++) {
(v, r, s) = signatureSplit(signatures, i);
if (v == 0) {
// If v is 0 then it is a contract signature
// When handling contract signatures the address of the contract is encoded into r
currentOwner = address(uint160(uint256(r)));
// Check that signature data pointer (s) is not pointing inside the static part of the signatures bytes
// This check is not completely accurate, since it is possible that more signatures than the threshold are send.
// Here we only check that the pointer is not pointing inside the part that is being processed
require(uint256(s) >= requiredSignatures.mul(65), "GS021");
// Check that signature data pointer (s) is in bounds (points to the length of data -> 32 bytes)
require(uint256(s).add(32) <= signatures.length, "GS022");
// Check if the contract signature is in bounds: start of data is s + 32 and end is start + signature length
uint256 contractSignatureLen;
// solhint-disable-next-line no-inline-assembly
assembly {
contractSignatureLen := mload(add(add(signatures, s), 0x20))
}
require(uint256(s).add(32).add(contractSignatureLen) <= signatures.length, "GS023");
// Check signature
bytes memory contractSignature;
// solhint-disable-next-line no-inline-assembly
assembly {
// The signature data for contract signatures is appended to the concatenated signatures and the offset is stored in s
contractSignature := add(add(signatures, s), 0x20)
}
require(ISignatureValidator(currentOwner).isValidSignature(data, contractSignature) == EIP1271_MAGIC_VALUE, "GS024");
} else if (v == 1) {
// If v is 1 then it is an approved hash
// When handling approved hashes the address of the approver is encoded into r
currentOwner = address(uint160(uint256(r)));
// Hashes are automatically approved by the sender of the message or when they have been pre-approved via a separate transaction
require(msg.sender == currentOwner || approvedHashes[currentOwner][dataHash] != 0, "GS025");
} else if (v > 30) {
// If v > 30 then default va (27,28) has been adjusted for eth_sign flow
// To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover
currentOwner = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", dataHash)), v - 4, r, s);
} else {
// Default is the ecrecover flow with the provided data hash
// Use ecrecover with the messageHash for EOA signatures
currentOwner = ecrecover(dataHash, v, r, s);
}
require(currentOwner > lastOwner && owners[currentOwner] != address(0) && currentOwner != SENTINEL_OWNERS, "GS026");
lastOwner = currentOwner;
}
}
/// @dev Allows to estimate a Safe transaction.
/// This method is only meant for estimation purpose, therefore the call will always revert and encode the result in the revert data.
/// Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the safe with `execTransaction`
/// @param to Destination address of Safe transaction.
/// @param value Ether value of Safe transaction.
/// @param data Data payload of Safe transaction.
/// @param operation Operation type of Safe transaction.
/// @return Estimate without refunds and overhead fees (base transaction and payload data gas costs).
/// @notice Deprecated in favor of common/StorageAccessible.sol and will be removed in next version.
function requiredTxGas(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation
) external returns (uint256) {
uint256 startGas = gasleft();
// We don't provide an error message here, as we use it to return the estimate
require(execute(to, value, data, operation, gasleft()));
uint256 requiredGas = startGas - gasleft();
// Convert response to string and return via error message
revert(string(abi.encodePacked(requiredGas)));
}
/**
* @dev Marks a hash as approved. This can be used to validate a hash that is used by a signature.
* @param hashToApprove The hash that should be marked as approved for signatures that are verified by this contract.
*/
function approveHash(bytes32 hashToApprove) external {
require(owners[msg.sender] != address(0), "GS030");
approvedHashes[msg.sender][hashToApprove] = 1;
emit ApproveHash(hashToApprove, msg.sender);
}
/// @dev Returns the chain id used by this contract.
function getChainId() public view returns (uint256) {
uint256 id;
// solhint-disable-next-line no-inline-assembly
assembly {
id := chainid()
}
return id;
}
function domainSeparator() public view returns (bytes32) {
return keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, getChainId(), this));
}
/// @dev Returns the bytes that are hashed to be signed by owners.
/// @param to Destination address.
/// @param value Ether value.
/// @param data Data payload.
/// @param operation Operation type.
/// @param safeTxGas Gas that should be used for the safe transaction.
/// @param baseGas Gas costs for that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
/// @param gasPrice Maximum gas price that should be used for this transaction.
/// @param gasToken Token address (or 0 if ETH) that is used for the payment.
/// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
/// @param _nonce Transaction nonce.
/// @return Transaction hash bytes.
function encodeTransactionData(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address refundReceiver,
uint256 _nonce
) public view returns (bytes memory) {
bytes32 safeTxHash =
keccak256(
abi.encode(
SAFE_TX_TYPEHASH,
to,
value,
keccak256(data),
operation,
safeTxGas,
baseGas,
gasPrice,
gasToken,
refundReceiver,
_nonce
)
);
return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator(), safeTxHash);
}
/// @dev Returns hash to be signed by owners.
/// @param to Destination address.
/// @param value Ether value.
/// @param data Data payload.
/// @param operation Operation type.
/// @param safeTxGas Fas that should be used for the safe transaction.
/// @param baseGas Gas costs for data used to trigger the safe transaction.
/// @param gasPrice Maximum gas price that should be used for this transaction.
/// @param gasToken Token address (or 0 if ETH) that is used for the payment.
/// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
/// @param _nonce Transaction nonce.
/// @return Transaction hash.
function getTransactionHash(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address refundReceiver,
uint256 _nonce
) public view returns (bytes32) {
return keccak256(encodeTransactionData(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce));
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title Multi Send - Allows to batch multiple transactions into one.
/// @author Nick Dodson - <[email protected]>
/// @author Gonçalo Sá - <[email protected]>
/// @author Stefan George - <[email protected]>
/// @author Richard Meissner - <[email protected]>
contract MultiSend {
address private immutable multisendSingleton;
constructor() {
multisendSingleton = address(this);
}
/// @dev Sends multiple transactions and reverts all if one fails.
/// @param transactions Encoded transactions. Each transaction is encoded as a packed bytes of
/// operation as a uint8 with 0 for a call or 1 for a delegatecall (=> 1 byte),
/// to as a address (=> 20 bytes),
/// value as a uint256 (=> 32 bytes),
/// data length as a uint256 (=> 32 bytes),
/// data as bytes.
/// see abi.encodePacked for more information on packed encoding
/// @notice This method is payable as delegatecalls keep the msg.value from the previous call
/// If the calling method (e.g. execTransaction) received ETH this would revert otherwise
function multiSend(bytes memory transactions) public payable {
require(address(this) != multisendSingleton, "MultiSend should only be called via delegatecall");
// solhint-disable-next-line no-inline-assembly
assembly {
let length := mload(transactions)
let i := 0x20
for {
// Pre block is not used in "while mode"
} lt(i, length) {
// Post block is not used in "while mode"
} {
// First byte of the data is the operation.
// We shift by 248 bits (256 - 8 [operation byte]) it right since mload will always load 32 bytes (a word).
// This will also zero out unused data.
let operation := shr(0xf8, mload(add(transactions, i)))
// We offset the load address by 1 byte (operation byte)
// We shift it right by 96 bits (256 - 160 [20 address bytes]) to right-align the data and zero out unused data.
let to := shr(0x60, mload(add(transactions, add(i, 0x01))))
// We offset the load address by 21 byte (operation byte + 20 address bytes)
let value := mload(add(transactions, add(i, 0x15)))
// We offset the load address by 53 byte (operation byte + 20 address bytes + 32 value bytes)
let dataLength := mload(add(transactions, add(i, 0x35)))
// We offset the load address by 85 byte (operation byte + 20 address bytes + 32 value bytes + 32 data length bytes)
let data := add(transactions, add(i, 0x55))
let success := 0
switch operation
case 0 {
success := call(gas(), to, value, data, dataLength, 0, 0)
}
case 1 {
success := delegatecall(gas(), to, data, dataLength, 0, 0)
}
if eq(success, 0) {
revert(0, 0)
}
// Next entry starts at 85 byte + data length
i := add(i, add(0x55, dataLength))
}
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
/// @title Module Interface - A contract that can pass messages to a Module Manager contract if enabled by that contract.
pragma solidity >=0.7.0 <0.9.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "../interfaces/IAvatar.sol";
import "../factory/FactoryFriendly.sol";
import "../guard/Guardable.sol";
abstract contract Module is OwnableUpgradeable, FactoryFriendly, Guardable {
/// @dev Emitted each time the avatar is set.
event AvatarSet(address indexed previousAvatar, address indexed newAvatar);
/// @dev Address that this module will pass transactions to.
address public avatar;
/// @dev Sets the avatar to a new avatar (`newAvatar`).
/// @notice Can only be called by the current owner.
function setAvatar(address _avatar) public onlyOwner {
address previousAvatar = avatar;
avatar = _avatar;
emit AvatarSet(previousAvatar, _avatar);
}
/// @dev Passes a transaction to be executed by the avatar.
/// @notice Can only be called by this contract.
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction: 0 == call, 1 == delegate call.
function exec(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) internal returns (bool success) {
/// check if a transactioon guard is enabled.
if (guard != address(0)) {
IGuard(guard).checkTransaction(
/// Transaction info used by module transactions
to,
value,
data,
operation,
/// Zero out the redundant transaction information only used for Safe multisig transctions
0,
0,
0,
address(0),
payable(0),
bytes("0x"),
address(0)
);
}
success = IAvatar(avatar).execTransactionFromModule(
to,
value,
data,
operation
);
if (guard != address(0)) {
IGuard(guard).checkAfterExecution(bytes32("0x"), success);
}
return success;
}
/// @dev Passes a transaction to be executed by the avatar and returns data.
/// @notice Can only be called by this contract.
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction: 0 == call, 1 == delegate call.
function execAndReturnData(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) internal returns (bool success, bytes memory returnData) {
/// check if a transactioon guard is enabled.
if (guard != address(0)) {
IGuard(guard).checkTransaction(
/// Transaction info used by module transactions
to,
value,
data,
operation,
/// Zero out the redundant transaction information only used for Safe multisig transctions
0,
0,
0,
address(0),
payable(0),
bytes("0x"),
address(0)
);
}
(success, returnData) = IAvatar(avatar)
.execTransactionFromModuleReturnData(to, value, data, operation);
if (guard != address(0)) {
IGuard(guard).checkAfterExecution(bytes32("0x"), success);
}
return (success, returnData);
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.8.0;
contract ModuleProxyFactory {
event ModuleProxyCreation(
address indexed proxy,
address indexed masterCopy
);
function createProxy(address target, bytes32 salt)
internal
returns (address result)
{
require(
address(target) != address(0),
"createProxy: address can not be zero"
);
bytes memory deployment = abi.encodePacked(
hex"3d602d80600a3d3981f3363d3d373d3d3d363d73",
target,
hex"5af43d82803e903d91602b57fd5bf3"
);
// solhint-disable-next-line no-inline-assembly
assembly {
result := create2(0, add(deployment, 0x20), mload(deployment), salt)
}
require(result != address(0), "createProxy: address already taken");
}
function deployModule(
address masterCopy,
bytes memory initializer,
uint256 saltNonce
) public returns (address proxy) {
proxy = createProxy(
masterCopy,
keccak256(abi.encodePacked(keccak256(initializer), saltNonce))
);
(bool success, ) = proxy.call(initializer);
require(success, "deployModule: initialization failed");
emit ModuleProxyCreation(proxy, masterCopy);
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "../common/Enum.sol";
import "../common/SelfAuthorized.sol";
import "./Executor.sol";
/// @title Module Manager - A contract that manages modules that can execute transactions via this contract
/// @author Stefan George - <[email protected]>
/// @author Richard Meissner - <[email protected]>
contract ModuleManager is SelfAuthorized, Executor {
event EnabledModule(address module);
event DisabledModule(address module);
event ExecutionFromModuleSuccess(address indexed module);
event ExecutionFromModuleFailure(address indexed module);
address internal constant SENTINEL_MODULES = address(0x1);
mapping(address => address) internal modules;
function setupModules(address to, bytes memory data) internal {
require(modules[SENTINEL_MODULES] == address(0), "GS100");
modules[SENTINEL_MODULES] = SENTINEL_MODULES;
if (to != address(0))
// Setup has to complete successfully or transaction fails.
require(execute(to, 0, data, Enum.Operation.DelegateCall, gasleft()), "GS000");
}
/// @dev Allows to add a module to the whitelist.
/// This can only be done via a Safe transaction.
/// @notice Enables the module `module` for the Safe.
/// @param module Module to be whitelisted.
function enableModule(address module) public authorized {
// Module address cannot be null or sentinel.
require(module != address(0) && module != SENTINEL_MODULES, "GS101");
// Module cannot be added twice.
require(modules[module] == address(0), "GS102");
modules[module] = modules[SENTINEL_MODULES];
modules[SENTINEL_MODULES] = module;
emit EnabledModule(module);
}
/// @dev Allows to remove a module from the whitelist.
/// This can only be done via a Safe transaction.
/// @notice Disables the module `module` for the Safe.
/// @param prevModule Module that pointed to the module to be removed in the linked list
/// @param module Module to be removed.
function disableModule(address prevModule, address module) public authorized {
// Validate module address and check that it corresponds to module index.
require(module != address(0) && module != SENTINEL_MODULES, "GS101");
require(modules[prevModule] == module, "GS103");
modules[prevModule] = modules[module];
modules[module] = address(0);
emit DisabledModule(module);
}
/// @dev Allows a Module to execute a Safe transaction without any further confirmations.
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction.
function execTransactionFromModule(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) public virtual returns (bool success) {
// Only whitelisted modules are allowed.
require(msg.sender != SENTINEL_MODULES && modules[msg.sender] != address(0), "GS104");
// Execute transaction without further confirmations.
success = execute(to, value, data, operation, gasleft());
if (success) emit ExecutionFromModuleSuccess(msg.sender);
else emit ExecutionFromModuleFailure(msg.sender);
}
/// @dev Allows a Module to execute a Safe transaction without any further confirmations and return data
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction.
function execTransactionFromModuleReturnData(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) public returns (bool success, bytes memory returnData) {
success = execTransactionFromModule(to, value, data, operation);
// solhint-disable-next-line no-inline-assembly
assembly {
// Load free memory location
let ptr := mload(0x40)
// We allocate memory for the return data by setting the free memory location to
// current free memory location + data size + 32 bytes for data size value
mstore(0x40, add(ptr, add(returndatasize(), 0x20)))
// Store the size
mstore(ptr, returndatasize())
// Store the data
returndatacopy(add(ptr, 0x20), 0, returndatasize())
// Point the return data to the correct memory location
returnData := ptr
}
}
/// @dev Returns if an module is enabled
/// @return True if the module is enabled
function isModuleEnabled(address module) public view returns (bool) {
return SENTINEL_MODULES != module && modules[module] != address(0);
}
/// @dev Returns array of modules.
/// @param start Start of the page.
/// @param pageSize Maximum number of modules that should be returned.
/// @return array Array of modules.
/// @return next Start of the next page.
function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next) {
// Init array with max page size
array = new address[](pageSize);
// Populate return array
uint256 moduleCount = 0;
address currentModule = modules[start];
while (currentModule != address(0x0) && currentModule != SENTINEL_MODULES && moduleCount < pageSize) {
array[moduleCount] = currentModule;
currentModule = modules[currentModule];
moduleCount++;
}
next = currentModule;
// Set correct size of returned array
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(array, moduleCount)
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "../common/SelfAuthorized.sol";
/// @title OwnerManager - Manages a set of owners and a threshold to perform actions.
/// @author Stefan George - <[email protected]>
/// @author Richard Meissner - <[email protected]>
contract OwnerManager is SelfAuthorized {
event AddedOwner(address owner);
event RemovedOwner(address owner);
event ChangedThreshold(uint256 threshold);
address internal constant SENTINEL_OWNERS = address(0x1);
mapping(address => address) internal owners;
uint256 internal ownerCount;
uint256 internal threshold;
/// @dev Setup function sets initial storage of contract.
/// @param _owners List of Safe owners.
/// @param _threshold Number of required confirmations for a Safe transaction.
function setupOwners(address[] memory _owners, uint256 _threshold) internal {
// Threshold can only be 0 at initialization.
// Check ensures that setup function can only be called once.
require(threshold == 0, "GS200");
// Validate that threshold is smaller than number of added owners.
require(_threshold <= _owners.length, "GS201");
// There has to be at least one Safe owner.
require(_threshold >= 1, "GS202");
// Initializing Safe owners.
address currentOwner = SENTINEL_OWNERS;
for (uint256 i = 0; i < _owners.length; i++) {
// Owner address cannot be null.
address owner = _owners[i];
require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this) && currentOwner != owner, "GS203");
// No duplicate owners allowed.
require(owners[owner] == address(0), "GS204");
owners[currentOwner] = owner;
currentOwner = owner;
}
owners[currentOwner] = SENTINEL_OWNERS;
ownerCount = _owners.length;
threshold = _threshold;
}
/// @dev Allows to add a new owner to the Safe and update the threshold at the same time.
/// This can only be done via a Safe transaction.
/// @notice Adds the owner `owner` to the Safe and updates the threshold to `_threshold`.
/// @param owner New owner address.
/// @param _threshold New threshold.
function addOwnerWithThreshold(address owner, uint256 _threshold) public authorized {
// Owner address cannot be null, the sentinel or the Safe itself.
require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this), "GS203");
// No duplicate owners allowed.
require(owners[owner] == address(0), "GS204");
owners[owner] = owners[SENTINEL_OWNERS];
owners[SENTINEL_OWNERS] = owner;
ownerCount++;
emit AddedOwner(owner);
// Change threshold if threshold was changed.
if (threshold != _threshold) changeThreshold(_threshold);
}
/// @dev Allows to remove an owner from the Safe and update the threshold at the same time.
/// This can only be done via a Safe transaction.
/// @notice Removes the owner `owner` from the Safe and updates the threshold to `_threshold`.
/// @param prevOwner Owner that pointed to the owner to be removed in the linked list
/// @param owner Owner address to be removed.
/// @param _threshold New threshold.
function removeOwner(
address prevOwner,
address owner,
uint256 _threshold
) public authorized {
// Only allow to remove an owner, if threshold can still be reached.
require(ownerCount - 1 >= _threshold, "GS201");
// Validate owner address and check that it corresponds to owner index.
require(owner != address(0) && owner != SENTINEL_OWNERS, "GS203");
require(owners[prevOwner] == owner, "GS205");
owners[prevOwner] = owners[owner];
owners[owner] = address(0);
ownerCount--;
emit RemovedOwner(owner);
// Change threshold if threshold was changed.
if (threshold != _threshold) changeThreshold(_threshold);
}
/// @dev Allows to swap/replace an owner from the Safe with another address.
/// This can only be done via a Safe transaction.
/// @notice Replaces the owner `oldOwner` in the Safe with `newOwner`.
/// @param prevOwner Owner that pointed to the owner to be replaced in the linked list
/// @param oldOwner Owner address to be replaced.
/// @param newOwner New owner address.
function swapOwner(
address prevOwner,
address oldOwner,
address newOwner
) public authorized {
// Owner address cannot be null, the sentinel or the Safe itself.
require(newOwner != address(0) && newOwner != SENTINEL_OWNERS && newOwner != address(this), "GS203");
// No duplicate owners allowed.
require(owners[newOwner] == address(0), "GS204");
// Validate oldOwner address and check that it corresponds to owner index.
require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "GS203");
require(owners[prevOwner] == oldOwner, "GS205");
owners[newOwner] = owners[oldOwner];
owners[prevOwner] = newOwner;
owners[oldOwner] = address(0);
emit RemovedOwner(oldOwner);
emit AddedOwner(newOwner);
}
/// @dev Allows to update the number of required confirmations by Safe owners.
/// This can only be done via a Safe transaction.
/// @notice Changes the threshold of the Safe to `_threshold`.
/// @param _threshold New threshold.
function changeThreshold(uint256 _threshold) public authorized {
// Validate that threshold is smaller than number of owners.
require(_threshold <= ownerCount, "GS201");
// There has to be at least one Safe owner.
require(_threshold >= 1, "GS202");
threshold = _threshold;
emit ChangedThreshold(threshold);
}
function getThreshold() public view returns (uint256) {
return threshold;
}
function isOwner(address owner) public view returns (bool) {
return owner != SENTINEL_OWNERS && owners[owner] != address(0);
}
/// @dev Returns array of owners.
/// @return Array of Safe owners.
function getOwners() public view returns (address[] memory) {
address[] memory array = new address[](ownerCount);
// populate return array
uint256 index = 0;
address currentOwner = owners[SENTINEL_OWNERS];
while (currentOwner != SENTINEL_OWNERS) {
array[index] = currentOwner;
currentOwner = owners[currentOwner];
index++;
}
return array;
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "../common/SelfAuthorized.sol";
/// @title Fallback Manager - A contract that manages fallback calls made to this contract
/// @author Richard Meissner - <[email protected]>
contract FallbackManager is SelfAuthorized {
event ChangedFallbackHandler(address handler);
// keccak256("fallback_manager.handler.address")
bytes32 internal constant FALLBACK_HANDLER_STORAGE_SLOT = 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5;
function internalSetFallbackHandler(address handler) internal {
bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, handler)
}
}
/// @dev Allows to add a contract to handle fallback calls.
/// Only fallback calls without value and with data will be forwarded.
/// This can only be done via a Safe transaction.
/// @param handler contract to handle fallbacks calls.
function setFallbackHandler(address handler) public authorized {
internalSetFallbackHandler(handler);
emit ChangedFallbackHandler(handler);
}
// solhint-disable-next-line payable-fallback,no-complex-fallback
fallback() external {
bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
let handler := sload(slot)
if iszero(handler) {
return(0, 0)
}
calldatacopy(0, 0, calldatasize())
// The msg.sender address is shifted to the left by 12 bytes to remove the padding
// Then the address without padding is stored right after the calldata
mstore(calldatasize(), shl(96, caller()))
// Add 20 bytes for the address appended add the end
let success := call(gas(), handler, 0, 0, add(calldatasize(), 20), 0, 0)
returndatacopy(0, 0, returndatasize())
if iszero(success) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "../common/Enum.sol";
import "../common/SelfAuthorized.sol";
interface Guard {
function checkTransaction(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver,
bytes memory signatures,
address msgSender
) external;
function checkAfterExecution(bytes32 txHash, bool success) external;
}
/// @title Fallback Manager - A contract that manages fallback calls made to this contract
/// @author Richard Meissner - <[email protected]>
contract GuardManager is SelfAuthorized {
event ChangedGuard(address guard);
// keccak256("guard_manager.guard.address")
bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8;
/// @dev Set a guard that checks transactions before execution
/// @param guard The address of the guard to be used or the 0 address to disable the guard
function setGuard(address guard) external authorized {
bytes32 slot = GUARD_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, guard)
}
emit ChangedGuard(guard);
}
function getGuard() internal view returns (address guard) {
bytes32 slot = GUARD_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
guard := sload(slot)
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title EtherPaymentFallback - A contract that has a fallback to accept ether payments
/// @author Richard Meissner - <[email protected]>
contract EtherPaymentFallback {
event SafeReceived(address indexed sender, uint256 value);
/// @dev Fallback function accepts Ether transactions.
receive() external payable {
emit SafeReceived(msg.sender, msg.value);
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title Singleton - Base for singleton contracts (should always be first super contract)
/// This contract is tightly coupled to our proxy contract (see `proxies/GnosisSafeProxy.sol`)
/// @author Richard Meissner - <[email protected]>
contract Singleton {
// singleton always needs to be first declared variable, to ensure that it is at the same location as in the Proxy contract.
// It should also always be ensured that the address is stored alone (uses a full word)
address private singleton;
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title SignatureDecoder - Decodes signatures that a encoded as bytes
/// @author Richard Meissner - <[email protected]>
contract SignatureDecoder {
/// @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s`.
/// @notice Make sure to peform a bounds check for @param pos, to avoid out of bounds access on @param signatures
/// @param pos which signature to read. A prior bounds check of this parameter should be performed, to avoid out of bounds access
/// @param signatures concatenated rsv signatures
function signatureSplit(bytes memory signatures, uint256 pos)
internal
pure
returns (
uint8 v,
bytes32 r,
bytes32 s
)
{
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
// solhint-disable-next-line no-inline-assembly
assembly {
let signaturePos := mul(0x41, pos)
r := mload(add(signatures, add(signaturePos, 0x20)))
s := mload(add(signatures, add(signaturePos, 0x40)))
// Here we are loading the last 32 bytes, including 31 bytes
// of 's'. There is no 'mload8' to do this.
//
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff)
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title SecuredTokenTransfer - Secure token transfer
/// @author Richard Meissner - <[email protected]>
contract SecuredTokenTransfer {
/// @dev Transfers a token and returns if it was a success
/// @param token Token that should be transferred
/// @param receiver Receiver to whom the token should be transferred
/// @param amount The amount of tokens that should be transferred
function transferToken(
address token,
address receiver,
uint256 amount
) internal returns (bool transferred) {
// 0xa9059cbb - keccack("transfer(address,uint256)")
bytes memory data = abi.encodeWithSelector(0xa9059cbb, receiver, amount);
// solhint-disable-next-line no-inline-assembly
assembly {
// We write the return value to scratch space.
// See https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html#layout-in-memory
let success := call(sub(gas(), 10000), token, 0, add(data, 0x20), mload(data), 0, 0x20)
switch returndatasize()
case 0 {
transferred := success
}
case 0x20 {
transferred := iszero(or(iszero(success), iszero(mload(0))))
}
default {
transferred := 0
}
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title StorageAccessible - generic base contract that allows callers to access all internal storage.
/// @notice See https://github.com/gnosis/util-contracts/blob/bb5fe5fb5df6d8400998094fb1b32a178a47c3a1/contracts/StorageAccessible.sol
contract StorageAccessible {
/**
* @dev Reads `length` bytes of storage in the currents contract
* @param offset - the offset in the current contract's storage in words to start reading from
* @param length - the number of words (32 bytes) of data to read
* @return the bytes that were read.
*/
function getStorageAt(uint256 offset, uint256 length) public view returns (bytes memory) {
bytes memory result = new bytes(length * 32);
for (uint256 index = 0; index < length; index++) {
// solhint-disable-next-line no-inline-assembly
assembly {
let word := sload(add(offset, index))
mstore(add(add(result, 0x20), mul(index, 0x20)), word)
}
}
return result;
}
/**
* @dev Performs a delegetecall on a targetContract in the context of self.
* Internally reverts execution to avoid side effects (making it static).
*
* This method reverts with data equal to `abi.encode(bool(success), bytes(response))`.
* Specifically, the `returndata` after a call to this method will be:
* `success:bool || response.length:uint256 || response:bytes`.
*
* @param targetContract Address of the contract containing the code to execute.
* @param calldataPayload Calldata that should be sent to the target contract (encoded method name and arguments).
*/
function simulateAndRevert(address targetContract, bytes memory calldataPayload) external {
// solhint-disable-next-line no-inline-assembly
assembly {
let success := delegatecall(gas(), targetContract, add(calldataPayload, 0x20), mload(calldataPayload), 0, 0)
mstore(0x00, success)
mstore(0x20, returndatasize())
returndatacopy(0x40, 0, returndatasize())
revert(0, add(returndatasize(), 0x40))
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
contract ISignatureValidatorConstants {
// bytes4(keccak256("isValidSignature(bytes,bytes)")
bytes4 internal constant EIP1271_MAGIC_VALUE = 0x20c13b0b;
}
abstract contract ISignatureValidator is ISignatureValidatorConstants {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param _data Arbitrary length data signed on the behalf of address(this)
* @param _signature Signature byte array associated with _data
*
* MUST return the bytes4 magic value 0x20c13b0b when function passes.
* MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
* MUST allow external calls
*/
function isValidSignature(bytes memory _data, bytes memory _signature) public view virtual returns (bytes4);
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/**
* @title GnosisSafeMath
* @dev Math operations with safety checks that revert on error
* Renamed from SafeMath to GnosisSafeMath to avoid conflicts
* TODO: remove once open zeppelin update to solc 0.5.0
*/
library GnosisSafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title Enum - Collection of enums
/// @author Richard Meissner - <[email protected]>
contract Enum {
enum Operation {Call, DelegateCall}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title SelfAuthorized - authorizes current contract to perform actions
/// @author Richard Meissner - <[email protected]>
contract SelfAuthorized {
function requireSelfCall() private view {
require(msg.sender == address(this), "GS031");
}
modifier authorized() {
// This is a function call as it minimized the bytecode size
requireSelfCall();
_;
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "../common/Enum.sol";
/// @title Executor - A contract that can execute transactions
/// @author Richard Meissner - <[email protected]>
contract Executor {
function execute(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 txGas
) internal returns (bool success) {
if (operation == Enum.Operation.DelegateCall) {
// solhint-disable-next-line no-inline-assembly
assembly {
success := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0)
}
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0)
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: LGPL-3.0-only
/// @title Zodiac Avatar - A contract that manages modules that can execute transactions via this contract.
pragma solidity >=0.7.0 <0.9.0;
import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol";
interface IAvatar {
/// @dev Enables a module on the avatar.
/// @notice Can only be called by the avatar.
/// @notice Modules should be stored as a linked list.
/// @notice Must emit EnabledModule(address module) if successful.
/// @param module Module to be enabled.
function enableModule(address module) external;
/// @dev Disables a module on the avatar.
/// @notice Can only be called by the avatar.
/// @notice Must emit DisabledModule(address module) if successful.
/// @param prevModule Address that pointed to the module to be removed in the linked list
/// @param module Module to be removed.
function disableModule(address prevModule, address module) external;
/// @dev Allows a Module to execute a transaction.
/// @notice Can only be called by an enabled module.
/// @notice Must emit ExecutionFromModuleSuccess(address module) if successful.
/// @notice Must emit ExecutionFromModuleFailure(address module) if unsuccessful.
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction: 0 == call, 1 == delegate call.
function execTransactionFromModule(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) external returns (bool success);
/// @dev Allows a Module to execute a transaction and return data
/// @notice Can only be called by an enabled module.
/// @notice Must emit ExecutionFromModuleSuccess(address module) if successful.
/// @notice Must emit ExecutionFromModuleFailure(address module) if unsuccessful.
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction: 0 == call, 1 == delegate call.
function execTransactionFromModuleReturnData(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) external returns (bool success, bytes memory returnData);
/// @dev Returns if an module is enabled
/// @return True if the module is enabled
function isModuleEnabled(address module) external view returns (bool);
/// @dev Returns array of modules.
/// @param start Start of the page.
/// @param pageSize Maximum number of modules that should be returned.
/// @return array Array of modules.
/// @return next Start of the next page.
function getModulesPaginated(address start, uint256 pageSize)
external
view
returns (address[] memory array, address next);
}
// SPDX-License-Identifier: LGPL-3.0-only
/// @title Zodiac FactoryFriendly - A contract that allows other contracts to be initializable and pass bytes as arguments to define contract state
pragma solidity >=0.7.0 <0.9.0;
abstract contract FactoryFriendly {
bool public initialized;
function setUp(bytes memory initializeParams) public virtual;
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@gnosis.pm/safe-contracts/contracts/interfaces/IERC165.sol";
import "./BaseGuard.sol";
/// @title Guardable - A contract that manages fallback calls made to this contract
contract Guardable is OwnableUpgradeable {
event ChangedGuard(address guard);
address public guard;
/// @dev Set a guard that checks transactions before execution
/// @param _guard The address of the guard to be used or the 0 address to disable the guard
function setGuard(address _guard) external onlyOwner {
if (_guard != address(0)) {
require(
BaseGuard(_guard).supportsInterface(type(IGuard).interfaceId),
"Guard does not implement IERC165"
);
}
guard = _guard;
emit ChangedGuard(guard);
}
function getGuard() external view returns (address _guard) {
return guard;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @notice More details at https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/introspection/IERC165.sol
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol";
import "@gnosis.pm/safe-contracts/contracts/interfaces/IERC165.sol";
import "../interfaces/IGuard.sol";
abstract contract BaseGuard is IERC165 {
function supportsInterface(bytes4 interfaceId)
external
pure
override
returns (bool)
{
return
interfaceId == type(IGuard).interfaceId || // 0xe6d7a83a
interfaceId == type(IERC165).interfaceId; // 0x01ffc9a7
}
/// Module transactions only use the first four parameters: to, value, data, and operation.
/// Module.sol hardcodes the remaining parameters as 0 since they are not used for module transactions.
/// This interface is used to maintain compatibilty with Gnosis Safe transaction guards.
function checkTransaction(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver,
bytes memory signatures,
address msgSender
) external virtual;
function checkAfterExecution(bytes32 txHash, bool success) external virtual;
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol";
interface IGuard {
function checkTransaction(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver,
bytes memory signatures,
address msgSender
) external;
function checkAfterExecution(bytes32 txHash, bool success) external;
}
|
Member accessible interface to withdraw funds from another Moloch directly to Safe or to the DAO Can only be called by member of Moloch _target MOLOCH address to withdraw from _token ERC20 address of token to withdraw _amount ERC20 token amount to withdraw Construct transaction data for safe to execute Transfers token into DAO.
|
function crossWithdraw(address _target, address _token, uint256 _amount, bool _transfer) external memberOnly {
bytes memory withdrawData = abi.encodeWithSelector(
IMOLOCH(_target).withdrawBalance.selector,
_token,
_amount
);
require(
exec(_target, 0, withdrawData, Operation.Call),
ERROR_CALL_FAIL
);
if(_transfer) {
bool whitelisted = moloch.tokenWhitelist(_token);
require(whitelisted, ERROR_NOT_WL);
bytes memory transferData = abi.encodeWithSelector(
IERC20(_token).transfer.selector,
address(moloch),
_amount
);
require(
exec(_token, 0, transferData, Operation.Call),
ERROR_CALL_FAIL
);
}
emit CrossWithdraw(_target, _token, _amount);
}
| 5,782,997 |
/**
*Submitted for verification at Etherscan.io on 2021-03-30
*/
// File: contracts/access/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: contracts/access/Ownable.sol
//pragma solidity ^0.6.0;
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function initialize() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/ExternalStub.sol
pragma solidity ^0.8.0;
/**
* @title Stub for BSC connection
* @dev Can be accessed by an authorized bridge/ValueHolder
*/
contract ExternalStub is Ownable {
bool private initialized;
address public ValueHolder;
address public enterToken; //= DAI_ADDRESS;
uint256 private PoolValue;
event LogValueHolderUpdated(address Manager);
/**
* @dev main init function
*/
function init(address _enterToken) external {
require(!initialized, "Initialized");
initialized = true;
Ownable.initialize(); // Do not forget this call!
_init(_enterToken);
}
/**
* @dev internal variable initialization
*/
function _init(address _enterToken) internal {
enterToken = _enterToken;
ValueHolder = msg.sender;
}
/**
* @dev re-initializer might be helpful for the cases where proxy's storage is corrupted by an old contact, but we cannot run init as we have the owner address already.
* This method might help fixing the storage state.
*/
function reInit(address _enterToken) external onlyOwner {
_init(_enterToken);
}
/**
* @dev this modifier is only for methods that should be called by ValueHolder contract
*/
modifier onlyValueHolder() {
require(msg.sender == ValueHolder, "Not Value Holder");
_;
}
/**
* @dev Sets new ValueHolder address
*/
function setValueHolder(address _ValueHolder) external onlyOwner {
ValueHolder = _ValueHolder;
emit LogValueHolderUpdated(_ValueHolder);
}
/**
* @dev Main function to enter Compound supply/borrow position using the available [DAI] token balance
*/
function addPosition() external pure {
revert("Stub");
}
/**
* @dev Main function to exit position - partially or completely
*/
function exitPosition(uint256) external pure {
revert("Stub");
}
/**
* @dev Get the total amount of enterToken value of the pool
*/
function getTokenStaked() external view returns (uint256) {
return (PoolValue);
}
/**
* @dev Get the total value the Pool in [denominateTo] tokens [DAI?]
*/
function getPoolValue(address) external view returns (uint256 totalValue) {
return (PoolValue);
}
/**
* @dev Get the total value the Pool in [denominateTo] tokens [DAI?]
*/
function setPoolValue(uint256 _PoolValue) external onlyValueHolder {
PoolValue = _PoolValue;
}
/**
* @dev Claim all available CRV from compound and convert to DAI as needed
*/
function claimValue() external pure {
revert("Stub");
}
}
|
Main function to enter Compound supply/borrow position using the available [DAI] token balance/
|
function addPosition() external pure {
revert("Stub");
}
| 10,844,267 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.