file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.13;
// Imports
import "./Ownable.sol";
import "./ReentrancyGuard.sol";
import "./IERC20.sol";
import "./IERC721.sol";
// MOD Interface
interface MODToken {
function mint(address recipient, uint256 amount) external;
}
/// @title MOD - Staking Contract
contract NFTStaking is Ownable, ReentrancyGuard {
// Staker details
struct Staker {
uint256[] tokenIds;
uint256 currentYield;
uint256 numberOfTokensStaked;
uint256 lastCheckpoint;
}
uint256 public constant SECONDS_IN_DAY = 24 * 60 * 60;
IERC721 public immutable nftContract;
MODToken public immutable rewardToken;
bool public stakingLaunched;
mapping(address => Staker) public stakers;
uint256 public lowYieldEndBound = 4;
uint256 public mediumYieldEndBound = 9;
uint256 public highYieldStartBound = 10;
uint256 public lowYieldPerSecond;
uint256 public mediumYieldPerSecond;
uint256 public highYieldPerSecond;
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
mapping(uint256 => address) private _ownerOfToken;
event Deposit(address indexed staker, uint256 amount);
event Withdraw(address indexed staker, uint256 amount);
event Claim(address indexed staker, uint256 tokenAmount);
/// @dev The contract constructor
constructor(
IERC721 _nftContract,
MODToken _rewardToken,
uint256 _lowYieldPerDay,
uint256 _mediumYieldPerDay,
uint256 _highYieldPerDay
) {
rewardToken = _rewardToken;
nftContract = _nftContract;
lowYieldPerSecond = _lowYieldPerDay / SECONDS_IN_DAY;
mediumYieldPerSecond = _mediumYieldPerDay / SECONDS_IN_DAY;
highYieldPerSecond = _highYieldPerDay / SECONDS_IN_DAY;
}
/**
* @param _lowYieldEndBound The upper bound of the lowest range that produces low yield
* @param _lowYieldPerDay The amount of tokens in Wei that a user earns for each token in the lowest range per day
* @param _mediumYieldEndBound The upper bound of the medium range that produces medium yield
* @param _mediumYieldPerDay The amount of tokens in Wei that a user earns for each token in the medium range per day
* @param _highYieldStartBound The lower bound of the highest range that produces high yield
* @param _highYieldPerDay The amount of tokens in Wei that a user earns for each token in the highest range per day
* @dev Sets yield parameters
*/
function setYieldParams(
uint256 _lowYieldEndBound,
uint256 _lowYieldPerDay,
uint256 _mediumYieldEndBound,
uint256 _mediumYieldPerDay,
uint256 _highYieldStartBound,
uint256 _highYieldPerDay
) external onlyOwner {
lowYieldEndBound = _lowYieldEndBound;
lowYieldPerSecond = _lowYieldPerDay / SECONDS_IN_DAY;
mediumYieldEndBound = _mediumYieldEndBound;
mediumYieldPerSecond = _mediumYieldPerDay / SECONDS_IN_DAY;
highYieldStartBound = _highYieldStartBound;
highYieldPerSecond = _highYieldPerDay / SECONDS_IN_DAY;
}
/**
* @param tokenIds The list of token IDs to stake
* @dev Stakes NFTs
*/
function deposit(uint256[] memory tokenIds) external nonReentrant {
require(stakingLaunched, "Staking is not launched yet");
Staker storage staker = stakers[_msgSender()];
if (staker.numberOfTokensStaked > 0) {
uint256 rewards = getUnclaimedRewards(_msgSender());
_claimReward(_msgSender(), rewards);
}
for (uint256 i; i < tokenIds.length; i++) {
require(nftContract.ownerOf(tokenIds[i]) == _msgSender(), "Not the owner");
nftContract.safeTransferFrom(_msgSender(), address(this), tokenIds[i]);
_ownerOfToken[tokenIds[i]] = _msgSender();
staker.tokenIds.push(tokenIds[i]);
staker.numberOfTokensStaked += 1;
}
staker.currentYield = getTotalYieldPerSecond(staker.numberOfTokensStaked);
staker.lastCheckpoint = block.timestamp;
emit Deposit(_msgSender(), tokenIds.length);
}
/**
* @param tokenIds The list of token IDs to unstake
* @dev Withdraws NFTs
*/
function withdraw(uint256[] memory tokenIds) external nonReentrant {
Staker storage staker = stakers[_msgSender()];
if (staker.numberOfTokensStaked > 0) {
uint256 rewards = getUnclaimedRewards(_msgSender());
_claimReward(_msgSender(), rewards);
}
for (uint256 i; i < tokenIds.length; i++) {
require(nftContract.ownerOf(tokenIds[i]) == address(this), "Invalid tokenIds provided");
require(_ownerOfToken[tokenIds[i]] == _msgSender(), "Not the owner of one ore more provided tokens");
_ownerOfToken[tokenIds[i]] = address(0);
staker.tokenIds = _moveTokenToLast(staker.tokenIds, tokenIds[i]);
staker.tokenIds.pop();
staker.numberOfTokensStaked -= 1;
nftContract.safeTransferFrom(address(this), _msgSender(), tokenIds[i]);
}
staker.currentYield = getTotalYieldPerSecond(staker.numberOfTokensStaked);
staker.lastCheckpoint = block.timestamp;
emit Withdraw(_msgSender(), tokenIds.length);
}
/// @dev Transfers reward to a user
function claimReward() external nonReentrant {
Staker storage staker = stakers[_msgSender()];
if (staker.numberOfTokensStaked > 0) {
uint256 rewards = getUnclaimedRewards(_msgSender());
_claimReward(_msgSender(), rewards);
}
staker.lastCheckpoint = block.timestamp;
}
/**
* @param tokenIds The list of token IDs to withdraw
* @dev Withdraws ERC721 in case of emergency
*/
function emergencyWithdraw(uint256[] memory tokenIds) external onlyOwner {
require(tokenIds.length <= 50, "50 is max per tx");
for (uint256 i; i < tokenIds.length; i++) {
address receiver = _ownerOfToken[tokenIds[i]];
if (receiver != address(0) && nftContract.ownerOf(tokenIds[i]) == address(this)) {
nftContract.transferFrom(address(this), receiver, tokenIds[i]);
}
}
}
/// @dev Starts NFT staking program
function launchStaking() external onlyOwner {
require(!stakingLaunched, "Staking has been launched already");
stakingLaunched = true;
}
/**
* @param balance The balance of a user
* @dev Gets total yield per second of all staked tokens of a user
*/
function getTotalYieldPerSecond(uint256 balance) public view returns (uint256) {
if (balance == 0) {
return 0;
}
if (balance <= lowYieldEndBound) {
return balance * lowYieldPerSecond;
} else if (balance <= mediumYieldEndBound) {
return lowYieldEndBound * lowYieldPerSecond + (balance - lowYieldEndBound) * mediumYieldPerSecond;
} else if (balance >= highYieldStartBound) {
uint256 lowYieldAmount = lowYieldEndBound;
uint256 mediumYieldAmount = mediumYieldEndBound - lowYieldEndBound;
uint256 highYieldAmount = balance - lowYieldAmount - mediumYieldAmount;
return lowYieldAmount * lowYieldPerSecond + mediumYieldAmount * mediumYieldPerSecond + highYieldAmount * highYieldPerSecond;
}
return 0;
}
/**
* @param staker The address of a user
* @dev Calculates unclaimed reward of a user
*/
function getUnclaimedRewards(address staker) public view returns (uint256) {
if (stakers[staker].lastCheckpoint == 0) {
return 0;
}
return (block.timestamp - stakers[staker].lastCheckpoint) * stakers[staker].currentYield;
}
/**
* @param staker The address of a user
* @dev Returns all token IDs staked by a user
*/
function getStakedTokens(address staker) public view returns (uint256[] memory) {
return stakers[staker].tokenIds;
}
/**
* @param staker The address of a user
* @dev Returns the number of tokens staked by a user
*/
function getTotalStakedAmount(address staker) public view returns (uint256) {
return stakers[staker].numberOfTokensStaked;
}
/// @dev Gets called whenever an IERC721 tokenId token is transferred to this contract via IERC721.safeTransferFrom
function onERC721Received(
address,
address,
uint256,
bytes calldata data
) public returns (bytes4) {
return _ERC721_RECEIVED;
}
/**
* @param list The array of token IDs
* @param tokenId The token ID to move to the end of the array
* @dev Moves the element that matches tokenId to the end of the array
*/
function _moveTokenToLast(uint256[] memory list, uint256 tokenId) internal pure returns (uint256[] memory) {
uint256 tokenIndex = 0;
uint256 lastTokenIndex = list.length - 1;
uint256 length = list.length;
for (uint256 i = 0; i < length; i++) {
if (list[i] == tokenId) {
tokenIndex = i + 1;
break;
}
}
require(tokenIndex != 0, "msg.sender is not the owner");
tokenIndex -= 1;
if (tokenIndex != lastTokenIndex) {
list[tokenIndex] = list[lastTokenIndex];
list[lastTokenIndex] = tokenId;
}
return list;
}
/**
* @param staker The user address
* @param amount The amount of tokens to claim
* @dev Transfers reward to a user
*/
function _claimReward(address staker, uint256 amount) private {
rewardToken.mint(staker, amount);
emit Claim(staker, amount);
}
} | staker The address of a user Returns all token IDs staked by a user/ | function getStakedTokens(address staker) public view returns (uint256[] memory) {
return stakers[staker].tokenIds;
}
| 1,421,416 |
/*
Copyright 2019 dYdX Trading 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.5.7;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { IDolomiteMargin } from "../../protocol/interfaces/IDolomiteMargin.sol";
import { Account } from "../../protocol/lib/Account.sol";
import { Actions } from "../../protocol/lib/Actions.sol";
import { Decimal } from "../../protocol/lib/Decimal.sol";
import { Interest } from "../../protocol/lib/Interest.sol";
import { DolomiteMarginMath } from "../../protocol/lib/DolomiteMarginMath.sol";
import { Monetary } from "../../protocol/lib/Monetary.sol";
import { Require } from "../../protocol/lib/Require.sol";
import { Time } from "../../protocol/lib/Time.sol";
import { Types } from "../../protocol/lib/Types.sol";
import { LiquidatorProxyHelper } from "../helpers/LiquidatorProxyHelper.sol";
import { IExpiry } from "../interfaces/IExpiry.sol";
import { DolomiteAmmRouterProxy } from "./DolomiteAmmRouterProxy.sol";
/**
* @title LiquidatorProxyV1WithAmm
* @author Dolomite
*
* Contract for liquidating other accounts in DolomiteMargin and atomically selling off collateral via Dolomite AMM
* markets.
*/
contract LiquidatorProxyV1WithAmm is ReentrancyGuard, LiquidatorProxyHelper {
using DolomiteMarginMath for uint256;
using SafeMath for uint256;
using Types for Types.Par;
using Types for Types.Wei;
// ============ Constants ============
bytes32 constant FILE = "LiquidatorProxyV1WithAmm";
// ============ Structs ============
struct Constants {
IDolomiteMargin dolomiteMargin;
Account.Info solidAccount;
Account.Info liquidAccount;
MarketInfo[] markets;
uint256[] liquidMarkets;
IExpiry expiryProxy;
uint32 expiry;
}
struct LiquidatorProxyWithAmmCache {
// mutable
uint256 toLiquidate;
// The amount of heldMarket the solidAccount will receive. Includes the liquidation reward.
uint256 solidHeldUpdateWithReward;
Types.Wei solidHeldWei;
Types.Wei liquidHeldWei;
Types.Wei liquidOwedWei;
// immutable
uint256 heldMarket;
uint256 owedMarket;
uint256 heldPrice;
uint256 owedPrice;
uint256 owedPriceAdj;
}
// ============ Events ============
/**
* @param solidAccountOwner The liquidator's address
* @param solidAccountOwner The liquidator's account number
* @param heldMarket The held market (collateral) that will be received by the liquidator
* @param heldDeltaWeiWithReward The amount of heldMarket the liquidator will receive, including the reward
* (positive number)
* @param profitHeldWei The amount of profit the liquidator will realize by performing the liquidation
* and atomically selling off the collateral. Can be negative or positive.
* @param owedMarket The debt market that will be received by the liquidator
* @param owedDeltaWei The amount of owedMarket that will be received by the liquidator (negative
* number)
*/
event LogLiquidateWithAmm(
address indexed solidAccountOwner,
uint solidAccountNumber,
uint heldMarket,
uint heldDeltaWeiWithReward,
Types.Wei profitHeldWei, // calculated as `heldWeiWithReward - soldHeldWeiToBreakEven`
uint owedMarket,
uint owedDeltaWei
);
// ============ Storage ============
IDolomiteMargin DOLOMITE_MARGIN;
DolomiteAmmRouterProxy ROUTER_PROXY;
IExpiry EXPIRY_PROXY;
// ============ Constructor ============
constructor (
address dolomiteMargin,
address dolomiteAmmRouterProxy,
address expiryProxy
)
public
{
DOLOMITE_MARGIN = IDolomiteMargin(dolomiteMargin);
ROUTER_PROXY = DolomiteAmmRouterProxy(dolomiteAmmRouterProxy);
EXPIRY_PROXY = IExpiry(expiryProxy);
}
// ============ Public Functions ============
/**
* Liquidate liquidAccount using solidAccount. This contract and the msg.sender to this contract
* must both be operators for the solidAccount.
*
* @param solidAccount The account that will do the liquidating
* @param liquidAccount The account that will be liquidated
* @param owedMarket The owed market whose borrowed value will be added to `toLiquidate`
* @param heldMarket The held market whose collateral will be recovered to take on the debt of
* `owedMarket`
* @param tokenPath The path through which the trade will be routed to recover the collateral
* @param expiry The time at which the position expires, if this liquidation is for closing
* an expired position. Else, 0.
* @param minOwedOutputAmount The minimum amount that should be outputted by the trade from heldWei to
* owedWei. Used to prevent sandwiching and mem-pool other attacks. Only used
* if `revertOnFailToSellCollateral` is set to `false` and the collateral
* cannot cover the `liquidAccount`'s debt.
* @param revertOnFailToSellCollateral True to revert the transaction completely if all collateral from the
* liquidation cannot repay the owed debt. False to swallow the error and sell
* whatever is possible. If set to false, the liquidator must have sufficient
* assets to be prevent becoming liquidated or under-collateralized.
*/
function liquidate(
Account.Info memory solidAccount,
Account.Info memory liquidAccount,
uint256 owedMarket,
uint256 heldMarket,
address[] memory tokenPath,
uint expiry,
uint minOwedOutputAmount,
bool revertOnFailToSellCollateral
)
public
nonReentrant
{
Require.that(
owedMarket != heldMarket,
FILE,
"owedMarket equals heldMarket",
owedMarket,
heldMarket
);
Require.that(
!DOLOMITE_MARGIN.getAccountPar(liquidAccount, owedMarket).isPositive(),
FILE,
"owed market cannot be positive",
owedMarket
);
Require.that(
DOLOMITE_MARGIN.getAccountPar(liquidAccount, heldMarket).isPositive(),
FILE,
"held market cannot be negative",
heldMarket
);
Require.that(
uint32(expiry) == expiry,
FILE,
"expiry overflow",
expiry
);
// put all values that will not change into a single struct
Constants memory constants;
constants.dolomiteMargin = DOLOMITE_MARGIN;
constants.solidAccount = solidAccount;
constants.liquidAccount = liquidAccount;
constants.liquidMarkets = constants.dolomiteMargin.getAccountMarketsWithBalances(liquidAccount);
constants.markets = getMarketInfos(
constants.dolomiteMargin,
constants.dolomiteMargin.getAccountMarketsWithBalances(solidAccount),
constants.liquidMarkets
);
constants.expiryProxy = expiry > 0 ? EXPIRY_PROXY: IExpiry(address(0));
constants.expiry = uint32(expiry);
LiquidatorProxyWithAmmCache memory cache = initializeCache(
constants,
heldMarket,
owedMarket
);
// validate the msg.sender and that the liquidAccount can be liquidated
checkRequirements(
constants,
heldMarket,
owedMarket,
tokenPath
);
// get the max liquidation amount
calculateMaxLiquidationAmount(cache);
// if nothing to liquidate, do nothing
Require.that(
cache.toLiquidate != 0,
FILE,
"nothing to liquidate"
);
uint totalSolidHeldWei = cache.solidHeldUpdateWithReward;
if (cache.solidHeldWei.sign) {
// If the solid account has held wei, add the amount the solid account will receive from liquidation to its
// total held wei
// We do this so we can accurately track how much the solid account has (and will have after the swap), in
// case we need to input it exactly to Router#getParamsForSwapExactTokensForTokens
totalSolidHeldWei = totalSolidHeldWei.add(cache.solidHeldWei.value);
}
(
Account.Info[] memory accounts,
Actions.ActionArgs[] memory actions
) = ROUTER_PROXY.getParamsForSwapTokensForExactTokens(
constants.solidAccount.owner,
constants.solidAccount.number,
uint(- 1), // maxInputWei
cache.toLiquidate, // the amount of owedMarket that needs to be repaid. Exact output amount
tokenPath
);
if (cache.solidHeldUpdateWithReward >= actions[0].amount.value) {
uint profit = cache.solidHeldUpdateWithReward.sub(actions[0].amount.value);
uint _owedMarket = owedMarket; // used to prevent the "stack too deep" error
emit LogLiquidateWithAmm(
constants.solidAccount.owner,
constants.solidAccount.number,
heldMarket,
cache.solidHeldUpdateWithReward,
Types.Wei(true, profit),
_owedMarket,
cache.toLiquidate
);
} else {
Require.that(
!revertOnFailToSellCollateral,
FILE,
"totalSolidHeldWei is too small",
totalSolidHeldWei,
actions[0].amount.value
);
// This value needs to be calculated before `actions` is overwritten below with the new swap parameters
uint profit = actions[0].amount.value.sub(cache.solidHeldUpdateWithReward);
(accounts, actions) = ROUTER_PROXY.getParamsForSwapExactTokensForTokens(
constants.solidAccount.owner,
constants.solidAccount.number,
totalSolidHeldWei, // inputWei
minOwedOutputAmount,
tokenPath
);
uint _owedMarket = owedMarket; // used to prevent the "stack too deep" error
emit LogLiquidateWithAmm(
constants.solidAccount.owner,
constants.solidAccount.number,
heldMarket,
cache.solidHeldUpdateWithReward,
Types.Wei(false, profit),
_owedMarket,
cache.toLiquidate
);
}
accounts = constructAccountsArray(constants, accounts);
// execute the liquidations
constants.dolomiteMargin.operate(
accounts,
constructActionsArray(constants, cache, accounts, actions) //solium-disable-line arg-overflow
);
}
// ============ Calculation Functions ============
/**
* Calculate the additional owedAmount that can be liquidated until the collateralization of the
* liquidator account reaches the minLiquidatorRatio. By this point, the cache will be set such
* that the amount of owedMarket is non-positive and the amount of heldMarket is non-negative.
*/
function calculateMaxLiquidationAmount(
LiquidatorProxyWithAmmCache memory cache
)
private
pure
{
uint liquidHeldValue = cache.heldPrice.mul(cache.liquidHeldWei.value);
uint liquidOwedValue = cache.owedPriceAdj.mul(cache.liquidOwedWei.value);
if (liquidHeldValue <= liquidOwedValue) {
// The user is under-collateralized; there is no reward left to give
cache.solidHeldUpdateWithReward = cache.liquidHeldWei.value;
cache.toLiquidate = DolomiteMarginMath.getPartialRoundUp(cache.liquidHeldWei.value, cache.heldPrice, cache.owedPriceAdj);
} else {
cache.solidHeldUpdateWithReward = DolomiteMarginMath.getPartial(
cache.liquidOwedWei.value,
cache.owedPriceAdj,
cache.heldPrice
);
cache.toLiquidate = cache.liquidOwedWei.value;
}
}
// ============ Helper Functions ============
/**
* Make some basic checks before attempting to liquidate an account.
* - Require that the msg.sender has the permission to use the liquidator account
* - Require that the liquid account is liquidatable based on the accounts global value (all assets held and owed,
* not just what's being liquidated)
*/
function checkRequirements(
Constants memory constants,
uint256 heldMarket,
uint256 owedMarket,
address[] memory tokenPath
)
private
view
{
// check credentials for msg.sender
Require.that(
constants.solidAccount.owner == msg.sender
|| constants.dolomiteMargin.getIsLocalOperator(constants.solidAccount.owner, msg.sender),
FILE,
"Sender not operator",
constants.solidAccount.owner
);
Require.that(
constants.dolomiteMargin.getMarketIdByTokenAddress(tokenPath[0]) == heldMarket,
FILE,
"0-index token path incorrect",
tokenPath[0]
);
Require.that(
constants.dolomiteMargin.getMarketIdByTokenAddress(tokenPath[tokenPath.length - 1]) == owedMarket,
FILE,
"last-index token path incorrect",
tokenPath[tokenPath.length - 1]
);
if (constants.expiry == 0) {
// user is getting liquidated, not expired. Check liquid account is indeed liquid
(
Monetary.Value memory liquidSupplyValue,
Monetary.Value memory liquidBorrowValue
) = getAdjustedAccountValues(
constants.dolomiteMargin,
constants.markets,
constants.liquidAccount,
constants.liquidMarkets
);
Require.that(
liquidSupplyValue.value != 0,
FILE,
"Liquid account no supply"
);
Require.that(
constants.dolomiteMargin.getAccountStatus(constants.liquidAccount) == Account.Status.Liquid ||
!isCollateralized(
liquidSupplyValue.value,
liquidBorrowValue.value,
constants.dolomiteMargin.getMarginRatio()
),
FILE,
"Liquid account not liquidatable"
);
} else {
// check the expiration is valid; to get here we already know constants.expiry != 0
uint32 expiry = constants.expiryProxy.getExpiry(constants.liquidAccount, owedMarket);
Require.that(
expiry == constants.expiry,
FILE,
"expiry mismatch",
expiry,
constants.expiry
);
Require.that(
expiry <= Time.currentTime(),
FILE,
"Borrow not yet expired",
expiry
);
}
}
/**
* Returns true if the supplyValue over-collateralizes the borrowValue by the ratio.
*/
function isCollateralized(
uint256 supplyValue,
uint256 borrowValue,
Decimal.D256 memory ratio
)
private
pure
returns (bool)
{
uint256 requiredMargin = Decimal.mul(borrowValue, ratio);
return supplyValue >= borrowValue.add(requiredMargin);
}
// ============ Getter Functions ============
/**
* Pre-populates cache values for some pair of markets.
*/
function initializeCache(
Constants memory constants,
uint256 heldMarket,
uint256 owedMarket
)
private
view
returns (LiquidatorProxyWithAmmCache memory)
{
MarketInfo memory heldMarketInfo = binarySearch(constants.markets, heldMarket);
MarketInfo memory owedMarketInfo = binarySearch(constants.markets, owedMarket);
uint256 heldPrice = heldMarketInfo.price.value;
uint256 owedPrice = owedMarketInfo.price.value;
uint256 owedPriceAdj;
if (constants.expiry > 0) {
(, Monetary.Price memory owedPricePrice) = constants.expiryProxy.getSpreadAdjustedPrices(
heldMarket,
owedMarket,
constants.expiry
);
owedPriceAdj = owedPricePrice.value;
} else {
owedPriceAdj = Decimal.mul(
owedPrice,
Decimal.onePlus(constants.dolomiteMargin.getLiquidationSpreadForPair(heldMarket, owedMarket))
);
}
return LiquidatorProxyWithAmmCache({
toLiquidate: 0,
solidHeldUpdateWithReward: 0,
solidHeldWei: Interest.parToWei(
constants.dolomiteMargin.getAccountPar(constants.solidAccount, heldMarket),
heldMarketInfo.index
),
liquidHeldWei: Interest.parToWei(
constants.dolomiteMargin.getAccountPar(constants.liquidAccount, heldMarket),
heldMarketInfo.index
),
liquidOwedWei: Interest.parToWei(
constants.dolomiteMargin.getAccountPar(constants.liquidAccount, owedMarket),
owedMarketInfo.index
),
heldMarket: heldMarket,
owedMarket: owedMarket,
heldPrice: heldPrice,
owedPrice: owedPrice,
owedPriceAdj: owedPriceAdj
});
}
// ============ Operation-Construction Functions ============
function constructAccountsArray(
Constants memory constants,
Account.Info[] memory accountsForTrade
)
private
pure
returns (Account.Info[] memory)
{
Account.Info[] memory accounts = new Account.Info[](accountsForTrade.length + 1);
for (uint i = 0; i < accountsForTrade.length; i++) {
accounts[i] = accountsForTrade[i];
}
assert(
accounts[0].owner == constants.solidAccount.owner &&
accounts[0].number == constants.solidAccount.number
);
accounts[accounts.length - 1] = constants.liquidAccount;
return accounts;
}
function constructActionsArray(
Constants memory constants,
LiquidatorProxyWithAmmCache memory cache,
Account.Info[] memory accounts,
Actions.ActionArgs[] memory actionsForTrade
)
private
pure
returns (Actions.ActionArgs[] memory)
{
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](actionsForTrade.length + 1);
if (constants.expiry > 0) {
// First action is a trade for closing the expired account
// accountId is solidAccount; otherAccountId is liquidAccount
actions[0] = Actions.ActionArgs({
actionType: Actions.ActionType.Trade,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: cache.toLiquidate
}),
primaryMarketId: cache.owedMarket,
secondaryMarketId: cache.heldMarket,
otherAddress: address(constants.expiryProxy),
otherAccountId: accounts.length - 1,
data: abi.encode(cache.owedMarket, constants.expiry)
});
} else {
// First action is a liquidation
// accountId is solidAccount; otherAccountId is liquidAccount
actions[0] = Actions.ActionArgs({
actionType: Actions.ActionType.Liquidate,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: cache.toLiquidate
}),
primaryMarketId: cache.owedMarket,
secondaryMarketId: cache.heldMarket,
otherAddress: address(0),
otherAccountId: accounts.length - 1,
data: new bytes(0)
});
}
for (uint i = 0; i < actionsForTrade.length; i++) {
actions[i + 1] = actionsForTrade[i];
}
return actions;
}
}
| Liquidate liquidAccount using solidAccount. This contract and the msg.sender to this contract must both be operators for the solidAccount. solidAccount The account that will do the liquidating liquidAccount The account that will be liquidated owedMarket The owed market whose borrowed value will be added to `toLiquidate` heldMarket The held market whose collateral will be recovered to take on the debt of `owedMarket` tokenPath The path through which the trade will be routed to recover the collateral expiry The time at which the position expires, if this liquidation is for closing an expired position. Else, 0. minOwedOutputAmount The minimum amount that should be outputted by the trade from heldWei to owedWei. Used to prevent sandwiching and mem-pool other attacks. Only used if `revertOnFailToSellCollateral` is set to `false` and the collateral cannot cover the `liquidAccount`'s debt. revertOnFailToSellCollateral True to revert the transaction completely if all collateral from the liquidation cannot repay the owed debt. False to swallow the error and sell whatever is possible. If set to false, the liquidator must have sufficient assets to be prevent becoming liquidated or under-collateralized./ put all values that will not change into a single struct validate the msg.sender and that the liquidAccount can be liquidated get the max liquidation amount if nothing to liquidate, do nothing If the solid account has held wei, add the amount the solid account will receive from liquidation to its total held wei We do this so we can accurately track how much the solid account has (and will have after the swap), in case we need to input it exactly to RoutergetParamsForSwapExactTokensForTokens This value needs to be calculated before `actions` is overwritten below with the new swap parameters | function liquidate(
Account.Info memory solidAccount,
Account.Info memory liquidAccount,
uint256 owedMarket,
uint256 heldMarket,
address[] memory tokenPath,
uint expiry,
uint minOwedOutputAmount,
bool revertOnFailToSellCollateral
)
public
nonReentrant
{
Require.that(
owedMarket != heldMarket,
FILE,
"owedMarket equals heldMarket",
owedMarket,
heldMarket
);
Require.that(
!DOLOMITE_MARGIN.getAccountPar(liquidAccount, owedMarket).isPositive(),
FILE,
"owed market cannot be positive",
owedMarket
);
Require.that(
DOLOMITE_MARGIN.getAccountPar(liquidAccount, heldMarket).isPositive(),
FILE,
"held market cannot be negative",
heldMarket
);
Require.that(
uint32(expiry) == expiry,
FILE,
"expiry overflow",
expiry
);
Constants memory constants;
constants.dolomiteMargin = DOLOMITE_MARGIN;
constants.solidAccount = solidAccount;
constants.liquidAccount = liquidAccount;
constants.liquidMarkets = constants.dolomiteMargin.getAccountMarketsWithBalances(liquidAccount);
constants.markets = getMarketInfos(
constants.dolomiteMargin,
constants.dolomiteMargin.getAccountMarketsWithBalances(solidAccount),
constants.liquidMarkets
);
constants.expiryProxy = expiry > 0 ? EXPIRY_PROXY: IExpiry(address(0));
constants.expiry = uint32(expiry);
LiquidatorProxyWithAmmCache memory cache = initializeCache(
constants,
heldMarket,
owedMarket
);
checkRequirements(
constants,
heldMarket,
owedMarket,
tokenPath
);
calculateMaxLiquidationAmount(cache);
Require.that(
cache.toLiquidate != 0,
FILE,
"nothing to liquidate"
);
uint totalSolidHeldWei = cache.solidHeldUpdateWithReward;
if (cache.solidHeldWei.sign) {
totalSolidHeldWei = totalSolidHeldWei.add(cache.solidHeldWei.value);
}
(
Account.Info[] memory accounts,
Actions.ActionArgs[] memory actions
) = ROUTER_PROXY.getParamsForSwapTokensForExactTokens(
constants.solidAccount.owner,
constants.solidAccount.number,
tokenPath
);
if (cache.solidHeldUpdateWithReward >= actions[0].amount.value) {
uint profit = cache.solidHeldUpdateWithReward.sub(actions[0].amount.value);
emit LogLiquidateWithAmm(
constants.solidAccount.owner,
constants.solidAccount.number,
heldMarket,
cache.solidHeldUpdateWithReward,
Types.Wei(true, profit),
_owedMarket,
cache.toLiquidate
);
Require.that(
!revertOnFailToSellCollateral,
FILE,
"totalSolidHeldWei is too small",
totalSolidHeldWei,
actions[0].amount.value
);
uint profit = actions[0].amount.value.sub(cache.solidHeldUpdateWithReward);
(accounts, actions) = ROUTER_PROXY.getParamsForSwapExactTokensForTokens(
constants.solidAccount.owner,
constants.solidAccount.number,
minOwedOutputAmount,
tokenPath
);
emit LogLiquidateWithAmm(
constants.solidAccount.owner,
constants.solidAccount.number,
heldMarket,
cache.solidHeldUpdateWithReward,
Types.Wei(false, profit),
_owedMarket,
cache.toLiquidate
);
}
accounts = constructAccountsArray(constants, accounts);
accounts,
);
}
| 2,570,381 |
./full_match/5/0x7983443EdAf27a55b2652726449dDb8F4Bf3DE1a/sources/contracts/MONSTER.sol | Use the rest of the inherited claim function logic | function _transferTokensOnClaim(
address _receiver,
uint256 _tokenId,
uint256 _quantity
) internal override {
soul.burn(
_receiver,
0,
_quantity
);
ticket.burn(
_receiver,
0,
_quantity
);
super._transferTokensOnClaim(_receiver, _tokenId, _quantity);
}
| 1,858,354 |
./full_match/1/0x4B8092CdF0FF8473f7CAB01b267208Eb565943AD/sources/contracts/libraries/Percent.sol | Return true if the _percent with _decimals many decimals is valid and false otherwise | function isValidPercent(uint256 _percent, uint256 _decimals)
internal
pure
returns (bool)
{
return _isValidPercent(_percent, _decimals);
}
| 4,846,130 |
pragma solidity ^0.8.0; //SPDX-License-Identifier: GPL-3.0
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
// prevent re-entrancy attacks
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
contract nftMarket is ReentrancyGuard {
using Counters for Counters.Counter;
Counters.Counter private _itemIds; // total number of items ever created
Counters.Counter private _itemSold; // total number of items Sold
address payable owner; // owner of the smart contract
// people have to pay for their NFT on this marketplace
uint256 listingPrice = 0.035 ether;
constructor(){
owner = payable(msg.sender);
}
struct MarketItem {
uint itemId;
address nftContract;
uint256 tokenId;
address payable seller;
address payable owner;
uint256 price;
bool sold;
}
// the struct items looks like an array, can't access it without mapping
// this is the way to access Market item struc by passing an integer Id
mapping(uint256 => MarketItem) private idMarketItem;
// declare event to log activity when item is sold.
// note that event function does not use semi colon but uses comma.
event MarketItemCreated (
uint indexed itemId,
address indexed nftContract,
uint256 indexed tokenId,
address payable seller,
address payable owner,
uint256 price,
bool sold
);
// function to get the listing price
function getListingPrice() public view returns (uint256) {
return listingPrice;
}
function setListingPrice(uint _price) public returns (uint256) {
listingPrice = _price;
return listingPrice;
}
/// @notice create a function that manages MarketItem
function createMarketItem(
address nftContract,
uint256 tokenId,
uint256 price) public payable nonReentrant {
require(price > 0, "Price must be above zero");
require(msg.value == listingPrice, "Price must be equal to listing price");
// if (msg.value != listingPrice) {
// return "Price must be equal to listing price";
// Time to use the struc Market data above in line 21
_itemIds.increment(); // add 1 to the total number of items ever created
uint256 itemId = _itemIds.current();
// note when you define a struc, you use curly braces to define it and semi colon inside
// but when using it you call it as a function with open and close round brackets with commas to seperate the items
idMarketItem[itemId] = MarketItem(
itemId,
nftContract,
tokenId,
payable(msg.sender),
payable (address(0)), // no owner yet hence set as empty address
price,
false);
// transfering ownership of the NFT to the contract itself until someone wants to buy.
IERC721(nftContract).transferFrom(msg.sender, address(this), tokenId);
// log this transactions
emit MarketItemCreated(
itemId,
nftContract,
tokenId,
payable(msg.sender),
payable(address(0)), // address is zero because it hasn't been sold yet
price,
false);
}
/// @notice function to create a sale
function createMarketSale(
address nftContract,
uint256 itemId) public payable nonReentrant {
uint price = idMarketItem[itemId].price;
uint tokenId = idMarketItem[itemId].tokenId;
require(msg.value == price, "Please submit the asking price in order to complete the purchase");
//pay the seller the amount
idMarketItem[itemId].seller.transfer(msg.value);
// transfer the ownership from the contract itself to the buyer
IERC721(nftContract).transferFrom(address(this), msg.sender, tokenId);
idMarketItem[itemId].owner = payable(msg.sender); // mark new buyer as new owner
idMarketItem[itemId].sold = true; // mark that it has been sold
_itemSold.increment(); // increment the total number of item sold by 1
payable (owner).transfer(listingPrice); // pay owner of the contract the listing price
}
/// @notice total number of items unsold on our platform
function fetchMarketItems() public view returns (MarketItem[] memory){
uint itemCount = _itemIds.current(); // total number of items ever Created
// total number of items that are unsold = total number of items created - total number of items ever sold
uint unsoldItemCount = _itemIds.current() - _itemSold.current();
uint currentIndex = 0;
// Instanciate or Craete an array of MarketItem
MarketItem[] memory items = new MarketItem[](unsoldItemCount);
// loop through all items ever created
for(uint i =0; i < itemCount; i++) {
// check if the item has not been sold
// by checking if the owner field is empty
if(idMarketItem[i+1].owner == address(0)){
// yes, this item has never been sold
uint currentId = idMarketItem[i+1].itemId;
MarketItem storage currentItem = idMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items; //return array of all unsold items
}
/// @notice fetch the list of NFT's bought by the user
function fetchMyNFTs()public view returns (MarketItem[] memory) {
// get total number of items ever created
uint totalItemCount = _itemIds.current();
uint itemCount = 0;
uint currentIndex = 0;
for (uint i=0; i< totalItemCount; i++){
// get only the item that this user has bought/ is the owner
if (idMarketItem[i+1].owner == msg.sender) {
itemCount += 1; // total length of the array
}
}
MarketItem[] memory items = new MarketItem[](itemCount);
for(uint i = 0; i < totalItemCount; i++){
if (idMarketItem[i+1].owner == msg.sender){
uint currentId = idMarketItem[i+1].itemId;
MarketItem storage currentItem = idMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
/// @notice fetch the list of NFT's created by the user
function fetchItemsCreated() public view returns (MarketItem[] memory) {
// get total number of items ever created
uint totalItemCount = _itemIds.current();
uint itemCount = 0;
uint currentIndex = 0;
for (uint i=0; i< totalItemCount; i++){
// get only the item that this user has bought/ is the owner
if (idMarketItem[i+1].seller == msg.sender) {
itemCount += 1; // total length of the array
}
}
MarketItem[] memory items = new MarketItem[](itemCount);
for(uint i = 0; i < totalItemCount; i++){
if (idMarketItem[i+1].seller == msg.sender){
uint currentId = idMarketItem[i+1].itemId;
MarketItem storage currentItem = idMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
} | total number of items unsold on our platform total number of items that are unsold = total number of items created - total number of items ever sold Instanciate or Craete an array of MarketItem loop through all items ever created check if the item has not been sold by checking if the owner field is empty yes, this item has never been sold | function fetchMarketItems() public view returns (MarketItem[] memory){
uint unsoldItemCount = _itemIds.current() - _itemSold.current();
uint currentIndex = 0;
MarketItem[] memory items = new MarketItem[](unsoldItemCount);
for(uint i =0; i < itemCount; i++) {
if(idMarketItem[i+1].owner == address(0)){
uint currentId = idMarketItem[i+1].itemId;
MarketItem storage currentItem = idMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
}
| 15,862,034 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.4.21 <0.8.0;
pragma experimental ABIEncoderV2;
import "./GorenCoinToken.sol";
contract Election {
// Structs
struct Candidate {
string fullName;
uint256 voteCount;
}
struct Voter {
bool authorized;
bool voted;
uint256 vote;
}
// Fields
address payable public owner;
bool public voteLive;
GorenCoinToken public tokenContract;
uint256 public tokenPrice;
mapping(address => Voter) public voters;
Candidate[] public candidates;
uint256 public totalVotes;
uint256 public countCandidates;
event AddedCandidate(uint256 candidateID);
// Voted event
event votedEvent(uint256 indexed _candidateId);
// Modifiers
modifier ownerOnly() {
require(owner == msg.sender, "Not Owner");
_;
}
modifier authToVote() {
require(voteLive);
require(!voters[msg.sender].voted);
require(voters[msg.sender].authorized);
_;
}
// Constructor
constructor(GorenCoinToken _tokenContract, uint256 _tokenPrice) public {
owner = msg.sender;
tokenContract = _tokenContract;
tokenPrice = _tokenPrice;
addCandidate("test");
}
// Start Vote - Only by owner command
function startVote() public ownerOnly {
voteLive = true;
}
// End Vote - Triggered by time
function endVote() public ownerOnly returns (string memory) {
voteLive = false;
uint256 _winner = 999;
uint256 _maxVotes = 0;
for (uint256 i = 0; i < countCandidates; i++) {
if (candidates[i].voteCount >= _maxVotes) {
_maxVotes = candidates[i].voteCount;
_winner = i;
}
}
return candidates[_winner].fullName;
}
// Add new candidate
function addCandidate(string memory _fullName) public ownerOnly {
candidates.push(Candidate(_fullName, 0));
countCandidates += 1;
emit AddedCandidate(getNumOfCandidates());
}
// Get total num of candidates
function getNumOfCandidates() public view returns (uint256) {
return countCandidates;
}
// Autorize someone to vote - only by owner
function authorize(address _person) public ownerOnly {
voters[_person].authorized = true;
}
// Vote function with asserts
function vote(uint256 _voteIndex) public authToVote {
voters[msg.sender].vote = _voteIndex;
voters[msg.sender].voted = true;
candidates[_voteIndex].voteCount += 1;
totalVotes += 1;
tokenContract.transfer(msg.sender, 1);
emit votedEvent(_voteIndex);
}
// End Contract
function end() public ownerOnly {
selfdestruct(owner);
}
}
| End Vote - Triggered by time | function endVote() public ownerOnly returns (string memory) {
voteLive = false;
uint256 _winner = 999;
uint256 _maxVotes = 0;
for (uint256 i = 0; i < countCandidates; i++) {
if (candidates[i].voteCount >= _maxVotes) {
_maxVotes = candidates[i].voteCount;
_winner = i;
}
}
return candidates[_winner].fullName;
}
| 908,855 |
./full_match/84531/0x5a39b86bEc8003214d9dF2AFe63b3f7D34e6b312/sources/contracts/CoincheckerMultipleAddresses.sol | update balancestransfer tokens into contract | function createMultipleLocks(
address _tokenAddress,
address _withdrawalAddress,
uint256[] memory _amounts,
uint256[] memory _unlockTimes
)
public
payable
returns (uint256)
{
require(_amounts.length > 0, "CoincheckerLock: Amounts length must be more than 0");
require(_amounts.length == _unlockTimes.length, "CoincheckerLock: Amounts length must be equals to unlock times length");
uint256 firstId = depositId;
uint256 i;
for (i=0; i<_amounts.length; i++)
{
require(_amounts[i] > 0, "CoincheckerLock: All amounts must be more than 0");
require(_unlockTimes[i] < 10000000000, "CoincheckerLock: Unlock times must be less than 10000000000");
walletTokenBalance[_tokenAddress][_withdrawalAddress] = walletTokenBalance[_tokenAddress][_withdrawalAddress].add(_amounts[i]);
tokenBalance[_tokenAddress] = tokenBalance[_tokenAddress].add(_amounts[i]);
uint256 _id = depositId++;
lockedToken[_id].tokenAddress = _tokenAddress;
lockedToken[_id].withdrawalAddress = _withdrawalAddress;
lockedToken[_id].tokenAmount = _amounts[i];
lockedToken[_id].unlockTime = _unlockTimes[i];
lockedToken[_id].withdrawn = false;
allDepositIds.push(_id);
depositsByWithdrawalAddress[_withdrawalAddress].push(_id);
depositsByTokenAddress[_tokenAddress].push(_id);
require(
IERC20(_tokenAddress).transferFrom(msg.sender, address(this), _amounts[i]),
"CoincheckerLock: Unable to transfer the tokens"
);
}
if (depositFee > 0) {
depositFeeAddress.sendValue(depositFee);
}
emit MultipleTokensLocked(_tokenAddress, _withdrawalAddress);
return firstId;
}
| 14,316,113 |
pragma solidity ^0.5.10;
contract Oracle {
/** Contract Constructor
* @param ethPrice the starting price of ETH in USD, represented as 150000000 = 150.00 USD
* @dev The message sender is assigned as the contract administrator
*/
constructor (uint ethPrice) public {
admins[msg.sender] = true;
addAsset("ETHUSD", ethPrice);
}
Asset[] public assets;
uint[8][] private prices; // includes 6 decimal places, 12000000 = 12.000000
mapping(address => bool) public admins;
mapping(address => bool) public readers;
uint public constant UPDATE_TIME_MIN = 18 hours; // 18
uint public constant SETTLE_TIME_MIN = 5 days; // 5
uint public constant EDIT_TIME_MAX = 30 minutes; // allows oracle to rectify obvious mistakes
struct Asset {
bytes32 name;
uint8 currentDay;
uint lastUpdateTime;
uint lastSettleTime;
bool isFinalDay;
}
event AssetAdded(
uint indexed id,
bytes32 name,
uint price
);
event PriceUpdated(
uint indexed id,
bytes32 indexed name,
uint price,
uint timestamp,
uint8 dayNumber
);
event PriceCorrected(
uint indexed id,
bytes32 indexed name,
uint price,
uint timestamp,
uint8 dayNumber
);
modifier onlyAdmin()
{
require(admins[msg.sender]);
_;
}
/** Grant administrator priviledges to a user
* @param newAdmin the address to promote
*/
function addAdmin(address newAdmin)
public
onlyAdmin
{
admins[newAdmin] = true;
}
/** Add a new asset tracked by the Oracle
* @param _name the plaintext name of the asset
* @param _startPrice the starting price of the asset in USD * 10^6, eg 120000 = $0.120000
* @dev this should usually be called on a Settlement Day
* @return id the newly assigned ID of the asset
*/
function addAsset(bytes32 _name, uint _startPrice)
public
returns (uint _assetID)
{
require (admins[msg.sender] || msg.sender == address(this));
// Fill the asset struct
Asset memory asset;
asset.name = _name;
asset.currentDay = 0;
asset.lastUpdateTime = now;
asset.lastSettleTime = now - 5 days;
assets.push(asset);
uint[8] memory _prices;
_prices[0] = _startPrice;
prices.push(_prices);
emit AssetAdded(assets.length - 1, _name, _startPrice);
return assets.length - 1;
}
/** Quickly fix an erroneous price
* @param _assetID the id of the asset to change
* @param _newPrice the new price to change to
* @dev this must be called within 30 minutes of the lates price update occurence
*/
function editPrice(uint _assetID, uint _newPrice)
public
onlyAdmin
{
Asset storage asset = assets[_assetID];
require(now < asset.lastUpdateTime + EDIT_TIME_MAX);
prices[_assetID][asset.currentDay] = _newPrice;
emit PriceCorrected(_assetID, asset.name, _newPrice, now, asset.currentDay);
}
/** Grant an address permision to access private information about the assets
* @param newReader the address of the account to grant reading priviledges
* @dev this allows the reader to use the getCurrentPricesFunction
*/
function addReader(address newReader)
public
onlyAdmin
{
readers[newReader] = true;
}
/** Return the entire current price array for a given asset
* @param _assetID the asset id of the desired asset
* @return _priceHist the price array for the asset
* @dev only the admin and addresses granted readership may call this function
*/
function getAllPrices(uint _assetID)
public
view
returns (uint[8] memory _priceHist)
{
require (admins[msg.sender] || readers[msg.sender]);
_priceHist = prices[_assetID];
}
/** Return only the latest prices
* @param _assetID the asset id of the desired asset
* @return _price the latest price of the given asset
* @dev only the admin or a designated reader may call this function
*/
function getCurrentPrice(uint _assetID)
public
view
returns (uint _price)
{
require (admins[msg.sender] || readers[msg.sender]);
_price = prices[_assetID][assets[_assetID].currentDay];
}
/** Get the timestamp of the last price update time
* @param _assetID the asset id of the desired asset
* @return timestamp the price update timestamp
*/
function getLastUpdateTime(uint _assetID)
public
view
returns (uint timestamp)
{
timestamp = assets[_assetID].lastUpdateTime;
}
/** Get the timestamp of the last settle update time
* @param _assetID the asset id of the desired asset
* @return timestamp the settle timestamp
*/
function getLastSettleTime(uint _assetID)
public
view
returns (uint timestamp)
{
timestamp = assets[_assetID].lastSettleTime;
}
/**
* @param _assetID the asset id of the desired asset
* pulls the day relevant for new AssetSwap takes
*/
function getStartDay(uint _assetID)
public
view
returns (uint8 _startDay)
{
if (assets[_assetID].isFinalDay) _startDay = 7;
else if (assets[_assetID].currentDay == 7) _startDay = 1;
else _startDay = assets[_assetID].currentDay + 1;
}
/** Show if the current day is the final price update before settle
* @param _assetID the asset id of the desired asset
* @return true if it is the final day, false otherwise
* This makes sure the oracle cannot sneak it a settlement unaware
*/
function isFinalDay(uint _assetID)
public
view
returns (bool)
{
return assets[_assetID].isFinalDay;
}
/** Show if the last price update was a settle price update
* @param _assetID the asset id of the desired asset
* @return true if the last update was a settle, false otherwise
*/
function isSettleDay(uint _assetID)
public
view
returns (bool)
{
return (assets[_assetID].currentDay == 7);
}
/** Remove administrator priviledges from a user
* @param toRemove the address to demote
* @notice you may not remove yourself
*/
function removeAdmin(address toRemove)
public
onlyAdmin
{
require(toRemove != msg.sender);
admins[toRemove] = false;
}
/** Publishes an asset price. Does not initiate a settlement.
* @param _assetID the ID of the asset to update
* @param _price the current price of the asset * 10^6
* @param finalDayStatus true if this is the last intraweek price update (the next will be a settle)
* @dev this can only be called after the required time has elapsed since the most recent price update
* @dev if finalDayStatus is true this function cannot be called again until after settle
*/
function intraWeekPrice(uint _assetID, uint _price, bool finalDayStatus)
public
onlyAdmin
{
Asset storage asset = assets[_assetID];
// Prevent price update too early
require(now > asset.lastUpdateTime + UPDATE_TIME_MIN);
require(!asset.isFinalDay);
if (asset.currentDay == 7) {
asset.currentDay = 1;
uint[8] memory newPrices;
newPrices[0] = prices[_assetID][7];
newPrices[1] = _price;
prices[_assetID] = newPrices;
} else {
asset.currentDay = asset.currentDay + 1;
prices[_assetID][asset.currentDay] = _price;
asset.isFinalDay = finalDayStatus;
}
asset.lastUpdateTime = now;
emit PriceUpdated(_assetID, asset.name, _price, now, asset.currentDay);
}
/** Publishes an asset price. Does not initiate a settlement.
* @param _assetID the ID of the asset to update
* @param _price the current price of the asset * 10^6
* @dev this can only be called after the required time has elapsed since the most recent price update
* @dev if finalDayStatus is true this function cannot be called again until after settle
*/
function settlePrice(uint _assetID, uint _price)
public
onlyAdmin
{
Asset storage asset = assets[_assetID];
// Prevent price update too early
require(now > asset.lastUpdateTime + UPDATE_TIME_MIN);
require(asset.isFinalDay);
require(now > asset.lastSettleTime + SETTLE_TIME_MIN,
"Sufficient time must pass between weekly price updates.");
asset.currentDay = 7;
prices[_assetID][7] = _price;
asset.lastSettleTime = now;
asset.isFinalDay = false;
asset.lastUpdateTime = now;
emit PriceUpdated(_assetID, asset.name, _price, now, 7);
}
} | Add a new asset tracked by the Oracle _name the plaintext name of the asset _startPrice the starting price of the asset in USD 10^6, eg 120000 = $0.120000 this should usually be called on a Settlement Day return id the newly assigned ID of the asset/ Fill the asset struct | function addAsset(bytes32 _name, uint _startPrice)
public
returns (uint _assetID)
{
require (admins[msg.sender] || msg.sender == address(this));
Asset memory asset;
asset.name = _name;
asset.currentDay = 0;
asset.lastUpdateTime = now;
asset.lastSettleTime = now - 5 days;
assets.push(asset);
uint[8] memory _prices;
_prices[0] = _startPrice;
prices.push(_prices);
emit AssetAdded(assets.length - 1, _name, _startPrice);
return assets.length - 1;
}
| 7,243,037 |
// "SPDX-License-Identifier: Apache-2.0"
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../BaseRegistryStorage.sol";
import "../AccessControl/AccessControl.sol";
import "./IOwnershipRegistry.sol";
/**
* @title OwnershipRegistry
*/
contract OwnershipRegistry is BaseRegistryStorage, AccessControl, IOwnershipRegistry {
event UpdatedObligor (bytes32 assetId, address prevObligor, address newObligor);
event UpdatedBeneficiary(bytes32 assetId, address prevBeneficiary, address newBeneficiary);
/**
* @notice Update the address of the default beneficiary of cashflows going to the creator.
* @dev Can only be updated by the current creator beneficiary or by an authorized account.
* @param assetId id of the asset
* @param newCreatorBeneficiary address of the new beneficiary
*/
function setCreatorBeneficiary(
bytes32 assetId,
address newCreatorBeneficiary
)
external
override
{
address prevCreatorBeneficiary = assets[assetId].ownership.creatorBeneficiary;
require(
prevCreatorBeneficiary != address(0),
"AssetRegistry.setCreatorBeneficiary: ENTRY_DOES_NOT_EXIST"
);
require(
msg.sender == prevCreatorBeneficiary || hasAccess(assetId, msg.sig, msg.sender),
"AssetRegistry.setCreatorBeneficiary: UNAUTHORIZED_SENDER"
);
assets[assetId].ownership.creatorBeneficiary = newCreatorBeneficiary;
emit UpdatedBeneficiary(assetId, prevCreatorBeneficiary, newCreatorBeneficiary);
}
/**
* @notice Updates the address of the default beneficiary of cashflows going to the counterparty.
* @dev Can only be updated by the current counterparty beneficiary or by an authorized account.
* @param assetId id of the asset
* @param newCounterpartyBeneficiary address of the new beneficiary
*/
function setCounterpartyBeneficiary(
bytes32 assetId,
address newCounterpartyBeneficiary
)
external
override
{
address prevCounterpartyBeneficiary = assets[assetId].ownership.counterpartyBeneficiary;
require(
prevCounterpartyBeneficiary != address(0),
"AssetRegistry.setCounterpartyBeneficiary: ENTRY_DOES_NOT_EXIST"
);
require(
msg.sender == prevCounterpartyBeneficiary || hasAccess(assetId, msg.sig, msg.sender),
"AssetRegistry.setCounterpartyBeneficiary: UNAUTHORIZED_SENDER"
);
assets[assetId].ownership.counterpartyBeneficiary = newCounterpartyBeneficiary;
emit UpdatedBeneficiary(assetId, prevCounterpartyBeneficiary, newCounterpartyBeneficiary);
}
/**
* @notice Update the address of the obligor which has to fulfill obligations
* for the creator of the asset.
* @dev Can only be updated by an authorized account.
* @param assetId id of the asset
* @param newCreatorObligor address of the new creator obligor
*/
function setCreatorObligor (bytes32 assetId, address newCreatorObligor)
external
override
{
require(
hasAccess(assetId, msg.sig, msg.sender),
"AssetRegistry.setCreatorObligor: UNAUTHORIZED_SENDER"
);
address prevCreatorObligor = assets[assetId].ownership.creatorObligor;
assets[assetId].ownership.creatorObligor = newCreatorObligor;
emit UpdatedObligor(assetId, prevCreatorObligor, newCreatorObligor);
}
/**
* @notice Update the address of the counterparty which has to fulfill obligations
* for the counterparty of the asset.
* @dev Can only be updated by an authorized account.
* @param assetId id of the asset
* @param newCounterpartyObligor address of the new counterparty obligor
*/
function setCounterpartyObligor (bytes32 assetId, address newCounterpartyObligor)
external
override
{
require(
hasAccess(assetId, msg.sig, msg.sender),
"AssetRegistry.setCounterpartyObligor: UNAUTHORIZED_SENDER"
);
address prevCounterpartyObligor = assets[assetId].ownership.counterpartyObligor;
assets[assetId].ownership.counterpartyObligor = newCounterpartyObligor;
emit UpdatedObligor(assetId, prevCounterpartyObligor, newCounterpartyObligor);
}
/**
* @notice Retrieves the registered addresses of owners (creator, counterparty) of an asset.
* @param assetId id of the asset
* @return addresses of all owners of the asset
*/
function getOwnership(bytes32 assetId)
external
view
override
returns (AssetOwnership memory)
{
return assets[assetId].ownership;
}
}
| Retrieves the registered addresses of owners (creator, counterparty) of an asset. assetId id of the asset return addresses of all owners of the asset/ | function getOwnership(bytes32 assetId)
external
view
override
returns (AssetOwnership memory)
{
return assets[assetId].ownership;
}
| 6,424,744 |
./full_match/4/0x66ca57dc387DEeE28a7Da103d23b0590C3307541/sources/contracts/zhen2.sol | Unpauses all token transfers. See {ERC721Pausable} and {Pausable-_unpause}. Requirements: - the caller must have the `PAUSER_ROLE`./ | function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "__ZhenArt_init: must have pauser role to unpause");
_unpause();
}
| 12,409,447 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.6;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a + b) >= b, "SafeMath: Add Overflow");
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a - b) <= a, "SafeMath: Underflow");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b == 0 || (c = a * b) / b == a, "SafeMath: Mul Overflow");
}
function div(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b > 0, "SafeMath: Div by Zero");
c = a / b;
}
function to128(uint256 a) internal pure returns (uint128 c) {
require(a <= uint128(-1), "SafeMath: uint128 Overflow");
c = uint128(a);
}
}
library SoulSwapLibrary {
using SafeMath for uint;
// 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, 'SoulSwapLibrary: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'SoulSwapLibrary: ZERO_ADDRESS');
}
// 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) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'f3dcc3c6c6e34d3981dd429ac942301b9ebdd05de1be17f646b55476c44dc951' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(
address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = ISoulSwapPair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'SoulSwapLibrary: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'SoulSwapLibrary: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// 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) internal pure returns (uint amountOut) {
require(amountIn > 0, 'SoulSwapLibrary: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'SoulSwapLibrary: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'SoulSwapLibrary: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'SoulSwapLibrary: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(
address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'SoulSwapLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(
address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'SoulSwapLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
interface ISoulSwapPair {
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;
}
interface ISoulSwapFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
event SetFeeTo(address indexed user, address indexed _feeTo);
event SetMigrator(address indexed user, address indexed _migrator);
event FeeToSetter(address indexed user, address indexed _feeToSetter);
function feeTo() external view returns (address _feeTo);
function feeToSetter() external view returns (address _feeToSetter);
function migrator() external view returns (address _migrator);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setMigrator(address) external;
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IERC20Detailed {
// ERC20 Optional Views
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Views
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
// Mutative functions
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
// Events
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract InstantPrice {
using SafeMath for uint256;
address public constant WFTM_ADDRESS = 0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83; // WFTM
address public constant USDC_MARKET = 0x160653F02b6597E7Db00BA8cA826cf43D2f39556; // USDC-FTM
address public constant FACTORY_ADDRESS = 0x1120e150dA9def6Fe930f4fEDeD18ef57c0CA7eF; // SoulSwap Factory
function contractUsdTokensSum(address _contract, address[] memory _tokens) public view returns (uint256) {
uint256[] memory balances = getContractTokensBalanceOfArray(_contract, _tokens);
return usdcTokensSum(_tokens, balances);
}
function contractFtmTokensSum(address _contract, address[] memory _tokens) public view returns (uint256) {
uint256[] memory balances = getContractTokensBalanceOfArray(_contract, _tokens);
return ftmTokensSum(_tokens, balances);
}
function usdcTokensSum(address[] memory _tokens, uint256[] memory _balances) public view returns (uint256) {
uint256 ftmTokensSumAmount = ftmTokensSum(_tokens, _balances);
uint256 ftmPriceInUsdc = currentFtmPriceInUsdc();
return ftmTokensSumAmount.mul(ftmPriceInUsdc).div(1 ether);
}
function ftmTokensSum(address[] memory _tokens, uint256[] memory _balances) public view returns (uint256) {
uint256 len = _tokens.length;
require(len == _balances.length, "LENGTHS_NOT_EQUAL");
uint256 sum = 0;
for (uint256 i = 0; i < len; i++) {
_balances[i] = amountToNative(_balances[i], getTokenDecimals(_tokens[i]));
sum = sum.add(currentTokenFtmPrice(_tokens[i]).mul(_balances[i]).div(1 ether));
}
return sum;
}
function currentFtmPriceInUsdc() public view returns (uint256) {
return currentTokenPrice(USDC_MARKET, WFTM_ADDRESS);
}
function currentTokenUsdcPrice(address _token) public view returns (uint256 price) {
uint256 ftmPriceInUsdc = currentFtmPriceInUsdc();
uint256 tokenFtmPrice = currentTokenFtmPrice(_token);
return tokenFtmPrice.mul(ftmPriceInUsdc).div(1 ether);
}
function currentTokenFtmPrice(address _token) public view returns (uint256 price) {
if (_token == WFTM_ADDRESS) {
return uint256(1 ether);
}
address market = ISoulSwapFactory(FACTORY_ADDRESS).getPair(_token, WFTM_ADDRESS);
if (market == address(0)) {
market = ISoulSwapFactory(FACTORY_ADDRESS).getPair(WFTM_ADDRESS, _token);
return currentTokenPrice(market, _token);
} else {
return currentTokenPrice(market, _token);
}
}
function currentTokenPrice(address soulswapMarket, address _token) public view returns (uint256 price) {
(uint112 reserve0, uint112 reserve1, ) = ISoulSwapPair(soulswapMarket).getReserves();
address token0 = ISoulSwapPair(soulswapMarket).token0();
address token1 = ISoulSwapPair(soulswapMarket).token1();
uint8 tokenInDecimals = getTokenDecimals(_token);
uint8 tokenOutDecimals = getTokenDecimals(_token == token0 ? token1 : token0);
uint256 inAmount = 1 ether;
if (tokenInDecimals < uint8(18)) {
inAmount = inAmount.div(10**uint256(uint8(18) - tokenInDecimals));
}
price = SoulSwapLibrary.getAmountOut(
inAmount,
_token == token0 ? reserve0 : reserve1,
_token == token0 ? reserve1 : reserve0
);
if (tokenInDecimals > tokenOutDecimals) {
return price.mul(10**uint256(tokenInDecimals - tokenOutDecimals));
} else {
return price;
}
}
function getContractTokensBalanceOfArray(address _contract, address[] memory tokens)
public
view
returns (uint256[] memory balances)
{
uint256 len = tokens.length;
balances = new uint256[](len);
for (uint256 i = 0; i < len; i++) {
balances[i] = IERC20Detailed(tokens[i]).balanceOf(_contract);
}
}
function getTokenDecimals(address _token) public view returns (uint8 decimals) {
try IERC20Detailed(_token).decimals() returns (uint8 _decimals) {
decimals = _decimals;
} catch (
bytes memory /*lowLevelData*/
) {
decimals = uint8(18);
}
}
function amountToNative(uint256 amount, uint8 decimals) public pure returns (uint256) {
if (decimals == uint8(18)) {
return amount;
}
return amount.mul(10**uint256(uint8(18) - decimals));
}
} | given some amount of an asset and pair reserves, returns an equivalent amount of the other asset | function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'SoulSwapLibrary: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'SoulSwapLibrary: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
| 12,963,398 |
./partial_match/137/0x6d15Cd2eD2f8BfFEA3827AA8911aEEfA346ACf97/sources/MintplexOpenEditionPlusStandalone.sol | Update the maximum amount of tokens that can be minted by a unique wallet _newWalletMax the new max of tokens a wallet can mint. Must be >= 1/ | function setWalletMax(uint256 _newWalletMax) public onlyTeamOrOwner {
if(_newWalletMax == 0) revert ValueCannotBeZero();
MAX_WALLET_MINTS = _newWalletMax;
}
| 3,520,748 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.8;
//
/**
* @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;
}
}
//
/**
* @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);
}
//
/**
* @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);
}
}
}
}
//
/**
* @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 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 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;
}
}
//
/**
* @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.
*
* Credit: https://github.com/OpenZeppelin/openzeppelin-upgrades/blob/master/packages/core/contracts/Initializable.sol
*/
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;
}
//
/**
* @notice Interface for ERC20 token which supports minting new tokens.
*/
interface IERC20Mintable is IERC20 {
function mint(address _user, uint256 _amount) external;
}
//
/**
* @notice Interface for ERC20 token which supports mint and burn.
*/
interface IERC20MintableBurnable is IERC20Mintable {
function burn(uint256 _amount) external;
function burnFrom(address _user, uint256 _amount) external;
}
//
/**
* @notice ACoconut swap.
*/
contract ACoconutSwap is Initializable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @dev Token swapped between two underlying tokens.
*/
event TokenSwapped(address indexed buyer, address indexed tokenSold, address indexed tokenBought, uint256 amountSold, uint256 amountBought);
/**
* @dev New pool token is minted.
*/
event Minted(address indexed provider, uint256 mintAmount, uint256[] amounts, uint256 feeAmount);
/**
* @dev Pool token is redeemed.
*/
event Redeemed(address indexed provider, uint256 redeemAmount, uint256[] amounts, uint256 feeAmount);
/**
* @dev Fee is collected.
*/
event FeeCollected(address indexed feeRecipient, uint256 feeAmount);
uint256 public constant feeDenominator = 10 ** 10;
address[] public tokens;
uint256[] public precisions; // 10 ** (18 - token decimals)
uint256[] public balances; // Converted to 10 ** 18
uint256 public mintFee; // Mint fee * 10**10
uint256 public swapFee; // Swap fee * 10**10
uint256 public redeemFee; // Redeem fee * 10**10
address public feeRecipient;
address public poolToken;
uint256 public totalSupply; // The total amount of pool token minted by the swap.
// It might be different from the pool token supply as the pool token can have multiple minters.
address public governance;
mapping(address => bool) public admins;
bool public paused;
uint256 public initialA;
/**
* @dev Initialize the ACoconut Swap.
*/
function initialize(address[] memory _tokens, uint256[] memory _precisions, uint256[] memory _fees,
address _poolToken, uint256 _A) public initializer {
require(_tokens.length == _precisions.length, "input mismatch");
require(_fees.length == 3, "no fees");
for (uint256 i = 0; i < _tokens.length; i++) {
require(_tokens[i] != address(0x0), "token not set");
require(_precisions[i] != 0, "precision not set");
balances.push(0);
}
require(_poolToken != address(0x0), "pool token not set");
governance = msg.sender;
feeRecipient = msg.sender;
tokens = _tokens;
precisions = _precisions;
mintFee = _fees[0];
swapFee = _fees[1];
redeemFee = _fees[2];
poolToken = _poolToken;
initialA = _A;
// The swap must start with paused state!
paused = true;
}
/**
* @dev Returns the current value of A. This method might be updated in the future.
*/
function getA() public view returns (uint256) {
return initialA;
}
/**
* @dev Computes D given token balances.
* @param _balances Normalized balance of each token.
* @param _A Amplification coefficient from getA()
*/
function _getD(uint256[] memory _balances, uint256 _A) internal pure returns (uint256) {
uint256 sum = 0;
uint256 i = 0;
uint256 Ann = _A;
for (i = 0; i < _balances.length; i++) {
sum = sum.add(_balances[i]);
Ann = Ann.mul(_balances.length);
}
if (sum == 0) return 0;
uint256 prevD = 0;
uint256 D = sum;
for (i = 0; i < 255; i++) {
uint256 pD = D;
for (uint256 j = 0; j < _balances.length; j++) {
// pD = pD * D / (_x * balance.length)
pD = pD.mul(D).div(_balances[j].mul(_balances.length));
}
prevD = D;
// D = (Ann * sum + pD * balance.length) * D / ((Ann - 1) * D + (balance.length + 1) * pD)
D = Ann.mul(sum).add(pD.mul(_balances.length)).mul(D).div(Ann.sub(1).mul(D).add(_balances.length.add(1).mul(pD)));
if (D > prevD) {
if (D - prevD <= 1) break;
} else {
if (prevD - D <= 1) break;
}
}
return D;
}
/**
* @dev Computes token balance given D.
* @param _balances Converted balance of each token except token with index _j.
* @param _j Index of the token to calculate balance.
* @param _D The target D value.
* @param _A Amplification coeffient.
* @return Converted balance of the token with index _j.
*/
function _getY(uint256[] memory _balances, uint256 _j, uint256 _D, uint256 _A) internal pure returns (uint256) {
uint256 c = _D;
uint256 S_ = 0;
uint256 Ann = _A;
uint256 i = 0;
for (i = 0; i < _balances.length; i++) {
Ann = Ann.mul(_balances.length);
if (i == _j) continue;
S_ = S_.add(_balances[i]);
// c = c * D / (_x * N)
c = c.mul(_D).div(_balances[i].mul(_balances.length));
}
// c = c * D / (Ann * N)
c = c.mul(_D).div(Ann.mul(_balances.length));
// b = S_ + D / Ann
uint256 b = S_.add(_D.div(Ann));
uint256 prevY = 0;
uint256 y = _D;
// 255 since the result is 256 digits
for (i = 0; i < 255; i++) {
prevY = y;
// y = (y * y + c) / (2 * y + b - D)
y = y.mul(y).add(c).div(y.mul(2).add(b).sub(_D));
if (y > prevY) {
if (y - prevY <= 1) break;
} else {
if (prevY - y <= 1) break;
}
}
return y;
}
/**
* @dev Compute the amount of pool token that can be minted.
* @param _amounts Unconverted token balances.
* @return The amount of pool token minted.
*/
function getMintAmount(uint256[] calldata _amounts) external view returns (uint256, uint256) {
uint256[] memory _balances = balances;
require(_amounts.length == _balances.length, "invalid amount");
uint256 A = getA();
uint256 oldD = totalSupply;
uint256 i = 0;
for (i = 0; i < _balances.length; i++) {
if (_amounts[i] == 0) continue;
// balance = balance + amount * precision
_balances[i] = _balances[i].add(_amounts[i].mul(precisions[i]));
}
uint256 newD = _getD(_balances, A);
// newD should be bigger than or equal to oldD
uint256 mintAmount = newD.sub(oldD);
uint256 feeAmount = 0;
if (mintFee > 0) {
feeAmount = mintAmount.mul(mintFee).div(feeDenominator);
mintAmount = mintAmount.sub(feeAmount);
}
return (mintAmount, feeAmount);
}
/**
* @dev Mints new pool token.
* @param _amounts Unconverted token balances used to mint pool token.
* @param _minMintAmount Minimum amount of pool token to mint.
*/
function mint(uint256[] calldata _amounts, uint256 _minMintAmount) external nonReentrant {
uint256[] memory _balances = balances;
// If swap is paused, only admins can mint.
require(!paused || admins[msg.sender], "paused");
require(_balances.length == _amounts.length, "invalid amounts");
uint256 A = getA();
uint256 oldD = totalSupply;
uint256 i = 0;
for (i = 0; i < _balances.length; i++) {
if (_amounts[i] == 0) {
// Initial deposit requires all tokens provided!
require(oldD > 0, "zero amount");
continue;
}
_balances[i] = _balances[i].add(_amounts[i].mul(precisions[i]));
}
uint256 newD = _getD(_balances, A);
// newD should be bigger than or equal to oldD
uint256 mintAmount = newD.sub(oldD);
uint256 fee = mintFee;
uint256 feeAmount;
if (fee > 0) {
feeAmount = mintAmount.mul(fee).div(feeDenominator);
mintAmount = mintAmount.sub(feeAmount);
}
require(mintAmount >= _minMintAmount, "fewer than expected");
// Transfer tokens into the swap
for (i = 0; i < _amounts.length; i++) {
if (_amounts[i] == 0) continue;
// Update the balance in storage
balances[i] = _balances[i];
IERC20(tokens[i]).safeTransferFrom(msg.sender, address(this), _amounts[i]);
}
totalSupply = newD;
IERC20MintableBurnable(poolToken).mint(feeRecipient, feeAmount);
IERC20MintableBurnable(poolToken).mint(msg.sender, mintAmount);
emit Minted(msg.sender, mintAmount, _amounts, feeAmount);
}
/**
* @dev Computes the output amount after the swap.
* @param _i Token index to swap in.
* @param _j Token index to swap out.
* @param _dx Unconverted amount of token _i to swap in.
* @return Unconverted amount of token _j to swap out.
*/
function getSwapAmount(uint256 _i, uint256 _j, uint256 _dx) external view returns (uint256) {
uint256[] memory _balances = balances;
require(_i != _j, "same token");
require(_i < _balances.length, "invalid in");
require(_j < _balances.length, "invalid out");
require(_dx > 0, "invalid amount");
uint256 A = getA();
uint256 D = totalSupply;
// balance[i] = balance[i] + dx * precisions[i]
_balances[_i] = _balances[_i].add(_dx.mul(precisions[_i]));
uint256 y = _getY(_balances, _j, D, A);
// dy = (balance[j] - y - 1) / precisions[j] in case there was rounding errors
uint256 dy = _balances[_j].sub(y).sub(1).div(precisions[_j]);
if (swapFee > 0) {
dy = dy.sub(dy.mul(swapFee).div(feeDenominator));
}
return dy;
}
/**
* @dev Exchange between two underlying tokens.
* @param _i Token index to swap in.
* @param _j Token index to swap out.
* @param _dx Unconverted amount of token _i to swap in.
* @param _minDy Minimum token _j to swap out in converted balance.
*/
function swap(uint256 _i, uint256 _j, uint256 _dx, uint256 _minDy) external nonReentrant {
uint256[] memory _balances = balances;
// If swap is paused, only admins can swap.
require(!paused || admins[msg.sender], "paused");
require(_i != _j, "same token");
require(_i < _balances.length, "invalid in");
require(_j < _balances.length, "invalid out");
require(_dx > 0, "invalid amount");
uint256 A = getA();
uint256 D = totalSupply;
// balance[i] = balance[i] + dx * precisions[i]
_balances[_i] = _balances[_i].add(_dx.mul(precisions[_i]));
uint256 y = _getY(_balances, _j, D, A);
// dy = (balance[j] - y - 1) / precisions[j] in case there was rounding errors
uint256 dy = _balances[_j].sub(y).sub(1).div(precisions[_j]);
// Update token balance in storage
balances[_j] = y;
balances[_i] = _balances[_i];
uint256 fee = swapFee;
if (fee > 0) {
dy = dy.sub(dy.mul(fee).div(feeDenominator));
}
require(dy >= _minDy, "fewer than expected");
IERC20(tokens[_i]).safeTransferFrom(msg.sender, address(this), _dx);
// Important: When swap fee > 0, the swap fee is charged on the output token.
// Therefore, balances[j] < tokens[j].balanceOf(this)
// Since balances[j] is used to compute D, D is unchanged.
// collectFees() is used to convert the difference between balances[j] and tokens[j].balanceOf(this)
// into pool token as fees!
IERC20(tokens[_j]).safeTransfer(msg.sender, dy);
emit TokenSwapped(msg.sender, tokens[_i], tokens[_j], _dx, dy);
}
/**
* @dev Computes the amounts of underlying tokens when redeeming pool token.
* @param _amount Amount of pool tokens to redeem.
* @return Amounts of underlying tokens redeemed.
*/
function getRedeemProportionAmount(uint256 _amount) external view returns (uint256[] memory, uint256) {
uint256[] memory _balances = balances;
require(_amount > 0, "zero amount");
uint256 D = totalSupply;
uint256[] memory amounts = new uint256[](_balances.length);
uint256 feeAmount = 0;
if (redeemFee > 0) {
feeAmount = _amount.mul(redeemFee).div(feeDenominator);
// Redemption fee is charged with pool token before redemption.
_amount = _amount.sub(feeAmount);
}
for (uint256 i = 0; i < _balances.length; i++) {
// We might choose to use poolToken.totalSupply to compute the amount, but decide to use
// D in case we have multiple minters on the pool token.
amounts[i] = _balances[i].mul(_amount).div(D).div(precisions[i]);
}
return (amounts, feeAmount);
}
/**
* @dev Redeems pool token to underlying tokens proportionally.
* @param _amount Amount of pool token to redeem.
* @param _minRedeemAmounts Minimum amount of underlying tokens to get.
*/
function redeemProportion(uint256 _amount, uint256[] calldata _minRedeemAmounts) external nonReentrant {
uint256[] memory _balances = balances;
// If swap is paused, only admins can redeem.
require(!paused || admins[msg.sender], "paused");
require(_amount > 0, "zero amount");
require(_balances.length == _minRedeemAmounts.length, "invalid mins");
uint256 D = totalSupply;
uint256[] memory amounts = new uint256[](_balances.length);
uint256 fee = redeemFee;
uint256 feeAmount;
if (fee > 0) {
feeAmount = _amount.mul(fee).div(feeDenominator);
// Redemption fee is paid with pool token
// No conversion is needed as the pool token has 18 decimals
IERC20(poolToken).safeTransferFrom(msg.sender, feeRecipient, feeAmount);
_amount = _amount.sub(feeAmount);
}
for (uint256 i = 0; i < _balances.length; i++) {
// We might choose to use poolToken.totalSupply to compute the amount, but decide to use
// D in case we have multiple minters on the pool token.
uint256 tokenAmount = _balances[i].mul(_amount).div(D);
// Important: Underlying tokens must convert back to original decimals!
amounts[i] = tokenAmount.div(precisions[i]);
require(amounts[i] >= _minRedeemAmounts[i], "fewer than expected");
// Updates the balance in storage
balances[i] = _balances[i].sub(tokenAmount);
IERC20(tokens[i]).safeTransfer(msg.sender, amounts[i]);
}
totalSupply = D.sub(_amount);
// After reducing the redeem fee, the remaining pool tokens are burned!
IERC20MintableBurnable(poolToken).burnFrom(msg.sender, _amount);
emit Redeemed(msg.sender, _amount.add(feeAmount), amounts, feeAmount);
}
/**
* @dev Computes the amount when redeeming pool token to one specific underlying token.
* @param _amount Amount of pool token to redeem.
* @param _i Index of the underlying token to redeem to.
* @return Amount of underlying token that can be redeem to.
*/
function getRedeemSingleAmount(uint256 _amount, uint256 _i) external view returns (uint256, uint256) {
uint256[] memory _balances = balances;
require(_amount > 0, "zero amount");
require(_i < _balances.length, "invalid token");
uint256 A = getA();
uint256 D = totalSupply;
uint256 feeAmount = 0;
if (redeemFee > 0) {
feeAmount = _amount.mul(redeemFee).div(feeDenominator);
// Redemption fee is charged with pool token before redemption.
_amount = _amount.sub(feeAmount);
}
// The pool token amount becomes D - _amount
uint256 y = _getY(_balances, _i, D.sub(_amount), A);
// dy = (balance[i] - y - 1) / precisions[i] in case there was rounding errors
uint256 dy = _balances[_i].sub(y).sub(1).div(precisions[_i]);
return (dy, feeAmount);
}
/**
* @dev Redeem pool token to one specific underlying token.
* @param _amount Amount of pool token to redeem.
* @param _i Index of the token to redeem to.
* @param _minRedeemAmount Minimum amount of the underlying token to redeem to.
*/
function redeemSingle(uint256 _amount, uint256 _i, uint256 _minRedeemAmount) external nonReentrant {
uint256[] memory _balances = balances;
// If swap is paused, only admins can redeem.
require(!paused || admins[msg.sender], "paused");
require(_amount > 0, "zero amount");
require(_i < _balances.length, "invalid token");
uint256 A = getA();
uint256 D = totalSupply;
uint256 fee = redeemFee;
uint256 feeAmount = 0;
if (fee > 0) {
// Redemption fee is charged with pool token before redemption.
feeAmount = _amount.mul(fee).div(feeDenominator);
// No conversion is needed as the pool token has 18 decimals
IERC20(poolToken).safeTransferFrom(msg.sender, feeRecipient, feeAmount);
_amount = _amount.sub(feeAmount);
}
// y is converted(18 decimals)
uint256 y = _getY(_balances, _i, D.sub(_amount), A);
// dy is not converted
// dy = (balance[i] - y - 1) / precisions[i] in case there was rounding errors
uint256 dy = _balances[_i].sub(y).sub(1).div(precisions[_i]);
require(dy >= _minRedeemAmount, "fewer than expected");
// Updates token balance in storage
balances[_i] = y;
uint256[] memory amounts = new uint256[](_balances.length);
amounts[_i] = dy;
IERC20(tokens[_i]).safeTransfer(msg.sender, dy);
totalSupply = D.sub(_amount);
IERC20MintableBurnable(poolToken).burnFrom(msg.sender, _amount);
emit Redeemed(msg.sender, _amount.add(feeAmount), amounts, feeAmount);
}
/**
* @dev Compute the amount of pool token that needs to be redeemed.
* @param _amounts Unconverted token balances.
* @return The amount of pool token that needs to be redeemed.
*/
function getRedeemMultiAmount(uint256[] calldata _amounts) external view returns (uint256, uint256) {
uint256[] memory _balances = balances;
require(_amounts.length == balances.length, "length not match");
uint256 A = getA();
uint256 oldD = totalSupply;
for (uint256 i = 0; i < _balances.length; i++) {
if (_amounts[i] == 0) continue;
// balance = balance + amount * precision
_balances[i] = _balances[i].sub(_amounts[i].mul(precisions[i]));
}
uint256 newD = _getD(_balances, A);
// newD should be smaller than or equal to oldD
uint256 redeemAmount = oldD.sub(newD);
uint256 feeAmount = 0;
if (redeemFee > 0) {
redeemAmount = redeemAmount.mul(feeDenominator).div(feeDenominator.sub(redeemFee));
feeAmount = redeemAmount.sub(oldD.sub(newD));
}
return (redeemAmount, feeAmount);
}
/**
* @dev Redeems underlying tokens.
* @param _amounts Amounts of underlying tokens to redeem to.
* @param _maxRedeemAmount Maximum of pool token to redeem.
*/
function redeemMulti(uint256[] calldata _amounts, uint256 _maxRedeemAmount) external nonReentrant {
uint256[] memory _balances = balances;
require(_amounts.length == balances.length, "length not match");
// If swap is paused, only admins can redeem.
require(!paused || admins[msg.sender], "paused");
uint256 A = getA();
uint256 oldD = totalSupply;
uint256 i = 0;
for (i = 0; i < _balances.length; i++) {
if (_amounts[i] == 0) continue;
// balance = balance + amount * precision
_balances[i] = _balances[i].sub(_amounts[i].mul(precisions[i]));
}
uint256 newD = _getD(_balances, A);
// newD should be smaller than or equal to oldD
uint256 redeemAmount = oldD.sub(newD);
uint256 fee = redeemFee;
uint256 feeAmount = 0;
if (fee > 0) {
redeemAmount = redeemAmount.mul(feeDenominator).div(feeDenominator.sub(fee));
feeAmount = redeemAmount.sub(oldD.sub(newD));
// No conversion is needed as the pool token has 18 decimals
IERC20(poolToken).safeTransferFrom(msg.sender, feeRecipient, feeAmount);
}
require(redeemAmount <= _maxRedeemAmount, "more than expected");
// Updates token balances in storage.
balances = _balances;
uint256 burnAmount = redeemAmount.sub(feeAmount);
totalSupply = oldD.sub(burnAmount);
IERC20MintableBurnable(poolToken).burnFrom(msg.sender, burnAmount);
for (i = 0; i < _balances.length; i++) {
if (_amounts[i] == 0) continue;
IERC20(tokens[i]).safeTransfer(msg.sender, _amounts[i]);
}
emit Redeemed(msg.sender, redeemAmount, _amounts, feeAmount);
}
/**
* @dev Return the amount of fee that's not collected.
*/
function getPendingFeeAmount() external view returns (uint256) {
uint256[] memory _balances = balances;
uint256 A = getA();
uint256 oldD = totalSupply;
for (uint256 i = 0; i < _balances.length; i++) {
_balances[i] = IERC20(tokens[i]).balanceOf(address(this)).mul(precisions[i]);
}
uint256 newD = _getD(_balances, A);
return newD.sub(oldD);
}
/**
* @dev Collect fee based on the token balance difference.
*/
function collectFee() external returns (uint256) {
require(admins[msg.sender], "not admin");
uint256[] memory _balances = balances;
uint256 A = getA();
uint256 oldD = totalSupply;
for (uint256 i = 0; i < _balances.length; i++) {
_balances[i] = IERC20(tokens[i]).balanceOf(address(this)).mul(precisions[i]);
}
uint256 newD = _getD(_balances, A);
uint256 feeAmount = newD.sub(oldD);
if (feeAmount == 0) return 0;
balances = _balances;
totalSupply = newD;
address _feeRecipient = feeRecipient;
IERC20MintableBurnable(poolToken).mint(_feeRecipient, feeAmount);
emit FeeCollected(_feeRecipient, feeAmount);
return feeAmount;
}
/**
* @dev Updates the govenance address.
*/
function setGovernance(address _governance) external {
require(msg.sender == governance, "not governance");
governance = _governance;
}
/**
* @dev Updates the mint fee.
*/
function setMintFee(uint256 _mintFee) external {
require(msg.sender == governance, "not governance");
mintFee = _mintFee;
}
/**
* @dev Updates the swap fee.
*/
function setSwapFee(uint256 _swapFee) external {
require(msg.sender == governance, "not governance");
swapFee = _swapFee;
}
/**
* @dev Updates the redeem fee.
*/
function setRedeemFee(uint256 _redeemFee) external {
require(msg.sender == governance, "not governance");
redeemFee = _redeemFee;
}
/**
* @dev Updates the recipient of mint/swap/redeem fees.
*/
function setFeeRecipient(address _feeRecipient) external {
require(msg.sender == governance, "not governance");
require(_feeRecipient != address(0x0), "fee recipient not set");
feeRecipient = _feeRecipient;
}
/**
* @dev Updates the pool token.
*/
function setPoolToken(address _poolToken) external {
require(msg.sender == governance, "not governance");
require(_poolToken != address(0x0), "pool token not set");
poolToken = _poolToken;
}
/**
* @dev Pause mint/swap/redeem actions. Can unpause later.
*/
function pause() external {
require(msg.sender == governance, "not governance");
require(!paused, "paused");
paused = true;
}
/**
* @dev Unpause mint/swap/redeem actions.
*/
function unpause() external {
require(msg.sender == governance, "not governance");
require(paused, "not paused");
paused = false;
}
/**
* @dev Updates the admin role for the address.
* @param _account Address to update admin role.
* @param _allowed Whether the address is granted the admin role.
*/
function setAdmin(address _account, bool _allowed) external {
require(msg.sender == governance, "not governance");
require(_account != address(0x0), "account not set");
admins[_account] = _allowed;
}
} | Updates the admin role for the address. _account Address to update admin role. _allowed Whether the address is granted the admin role./ | function setAdmin(address _account, bool _allowed) external {
require(msg.sender == governance, "not governance");
require(_account != address(0x0), "account not set");
admins[_account] = _allowed;
}
| 312,628 |
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) {
if (a == 0 || b == 0) {
return 0;
}
c = a * b;
require(c / a == b, "Mul overflow!");
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity automatically throws when dividing by 0
uint256 c = a / b;
return c;
}
/**
* @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) {
require(b <= a, "Sub overflow!");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
require(c >= a, "Add overflow!");
return c;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
function balanceOf(address _owner) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns(bool);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
modifier onlyOwner {
require(msg.sender == owner, "Only Owner can do that!");
_;
}
function transferOwnership(address _newOwner)
external onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership()
external {
require(msg.sender == newOwner, "You are not new Owner!");
owner = newOwner;
newOwner = address(0);
emit OwnershipTransferred(owner, newOwner);
}
}
contract Permissioned {
function approve(address _spender, uint256 _value) public returns(bool);
function transferFrom(address _from, address _to, uint256 _value) external returns(bool);
function allowance(address _owner, address _spender) external view returns (uint256);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract Burnable {
function burn(uint256 _value) external returns(bool);
function burnFrom(address _from, uint256 _value) external returns(bool);
// This notifies clients about the amount burnt
event Burn(address indexed _from, uint256 _value);
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract Aligato is ERC20Interface, Owned, Permissioned, Burnable {
using SafeMath for uint256; //Be aware of overflows
// This creates an array with all balances
mapping(address => uint256) internal _balanceOf;
// This creates an array with all allowance
mapping(address => mapping(address => uint256)) internal _allowance;
bool public isLocked = true; //only contract Owner can transfer tokens
uint256 icoSupply = 0;
//set ICO balance and emit
function setICO(address user, uint256 amt) internal{
uint256 amt2 = amt * (10 ** uint256(decimals));
_balanceOf[user] = amt2;
emit Transfer(0x0, user, amt2);
icoSupply += amt2;
}
// As ICO been done on platform, we need set proper amouts for ppl that participate
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(string _symbol, string _name, uint256 _supply, uint8 _decimals)
public {
require(_supply != 0, "Supply required!"); //avoid accidental deplyment with zero balance
owner = msg.sender;
symbol = _symbol;
name = _name;
decimals = _decimals;
totalSupply = _supply.mul(10 ** uint256(decimals)); //supply in constuctor is w/o decimal zeros
_balanceOf[msg.sender] = totalSupply - icoSupply;
emit Transfer(address(0), msg.sender, totalSupply - icoSupply);
}
// unlock transfers for everyone
function unlock() external onlyOwner returns (bool success)
{
require (isLocked == true, "It is unlocked already!"); //you can unlock only once
isLocked = false;
return true;
}
/**
* Get the token balance for account
*
* Get token balance of `_owner` account
*
* @param _owner The address of the owner
*/
function balanceOf(address _owner)
external view
returns(uint256 balance) {
return _balanceOf[_owner];
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint256 _value)
internal {
// check that contract is unlocked
require (isLocked == false || _from == owner, "Contract is locked!");
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(0), "Can`t send to 0x0, use burn()");
// Check if the sender has enough
require(_balanceOf[_from] >= _value, "Not enough balance!");
// Subtract from the sender
_balanceOf[_from] = _balanceOf[_from].sub(_value);
// Add the same to the recipient
_balanceOf[_to] = _balanceOf[_to].add(_value);
emit Transfer(_from, _to, _value);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value)
external
returns(bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value)
external
returns(bool success) {
// Check allowance
require(_value <= _allowance[_from][msg.sender], "Not enough allowance!");
// Check balance
require(_value <= _balanceOf[_from], "Not enough balance!");
_allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value);
_transfer(_from, _to, _value);
emit Approval(_from, _to, _allowance[_from][_to]);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value)
public
returns(bool success) {
_allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
external
returns(bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
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)
external view
returns(uint256 value) {
return _allowance[_owner][_spender];
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value)
external
returns(bool success) {
_burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value)
external
returns(bool success) {
// Check allowance
require(_value <= _allowance[_from][msg.sender], "Not enough allowance!");
// Is tehere enough coins on account
require(_value <= _balanceOf[_from], "Insuffient balance!");
// Subtract from the sender's allowance
_allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value);
_burn(_from, _value);
emit Approval(_from, msg.sender, _allowance[_from][msg.sender]);
return true;
}
function _burn(address _from, uint256 _value)
internal {
// Check if the targeted balance is enough
require(_balanceOf[_from] >= _value, "Insuffient balance!");
// Subtract from the sender
_balanceOf[_from] = _balanceOf[_from].sub(_value);
// Updates totalSupply
totalSupply = totalSupply.sub(_value);
emit Burn(msg.sender, _value);
emit Transfer(_from, address(0), _value);
}
// ------------------------------------------------------------------------
// Don't accept accidental ETH
// ------------------------------------------------------------------------
function () external payable {
revert("This contract is not accepting ETH.");
}
//Owner can take ETH from contract
function withdraw(uint256 _amount)
external onlyOwner
returns (bool){
require(_amount <= address(this).balance, "Not enough balance!");
owner.transfer(_amount);
return true;
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint256 _value)
external onlyOwner
returns(bool success) {
return ERC20Interface(tokenAddress).transfer(owner, _value);
}
} | Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend)./ | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "Sub overflow!");
return a - b;
}
| 13,031,495 |
./partial_match/1/0xee319C50a873493d220e11946655270244D8e164/sources/src/ERC20StakingPool.sol | The amount of reward tokens an account has accrued so far. Does not include already withdrawn rewards. | function earned(address account) external view returns (uint256) {
return
_earned(
account,
balanceOf[account],
_rewardPerToken(
totalSupply,
lastTimeRewardApplicable(),
rewardRate
),
rewards[account]
);
}
| 4,265,605 |
./full_match/5/0x76f01394144a45741efccdA993837368D8031456/sources/contracts/Xen/xenClaimMod.sol | accepts User cRank claim provided all checks pass (incl. no current claim exists)/ Verify the merkle proof. Mark it claimed. create and store new MintInfo | function claim(uint256 index, address account, uint256 _amount, bytes32[] calldata merkleProof) external {
require(!isClaimed(index), "MerkleDistributor: Drop already claimed.");
bytes32 node = keccak256(abi.encodePacked(index, account, _amount));
require(MerkleProof.verify(merkleProof, merkleRoot, node), "MerkleDistributor: Invalid proof.");
_setClaimed(index);
MintInfo memory mintInfo = MintInfo({
user: _msgSender(),
amount: _amount
});
userMints[_msgSender()] = mintInfo;
activeMinters++;
emit Claimed(index, account, _amount);
}
| 11,607,487 |
./partial_match/1/0xAF5078bCEE5B9DE9Bb9394207Ca48ac32648C45f/sources/Workspace.sol | "Send" a "file" to this contract. File should be encrypted on this contract asymetricEncryptionPublicKey, before upload on decentralized file storage, before submitting a TX here./ | function identityboxSendfile(
uint _fileType, uint _fileEngine, bytes _fileHash
)
external
{
require(!identityboxBlacklisted[msg.sender], "You are blacklisted");
emit FileReceived(msg.sender, _fileType, _fileEngine, _fileHash);
}
| 3,939,190 |
pragma solidity ^0.5.7;
library SafeMath {
int256 constant private int256_min606 = -2**255; //inject NONSTANDARD NAMING
function MUL578(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-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function MUL578(int256 a, int256 b) internal pure returns (int256) { //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-solidity/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == int256_min606)); // This is the only case of overflow not detected by the check below
int256 c = a * b;
require(c / a == b);
return c;
}
function DIV266(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function DIV266(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING
require(b != 0); // Solidity only automatically asserts when dividing by 0
require(!(b == -1 && a == int256_min606)); // This is the only case of overflow
int256 c = a / b;
return c;
}
function SUB55(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function SUB55(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
function ADD666(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function ADD666(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
function MOD120(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
interface IERC20 {
function TOTALSUPPLY304() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF735(address who) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE123(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER854(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE531(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM522(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER418(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL780(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract ERC20Pistachio is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
// Token symbol (short)
string public symbol;
// Token name (Long)
string public name;
// Decimals (18 maximum)
uint8 public decimals;
constructor (address initialAccount, string memory _tokenSymbol, string memory _tokenName, uint256 initialBalance) public {
// Initialize Contract Parameters
symbol = _tokenSymbol;
name = _tokenName;
decimals = 18; // default decimals is going to be 18 always
_MINT600(initialAccount, initialBalance);
}
function TOTALSUPPLY304() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF735(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[owner];
}
function ALLOWANCE123(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowed[owner][spender];
}
function TRANSFER854(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER481(msg.sender, to, value);
return true;
}
function APPROVE531(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit APPROVAL780(msg.sender, spender, value);
return true;
}
function TRANSFERFROM522(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_allowed[from][msg.sender] = _allowed[from][msg.sender].SUB55(value);
_TRANSFER481(from, to, value);
emit APPROVAL780(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
function INCREASEALLOWANCE330(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].ADD666(addedValue);
emit APPROVAL780(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function DECREASEALLOWANCE446(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].SUB55(subtractedValue);
emit APPROVAL780(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _TRANSFER481(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
require(to != address(0));
_balances[from] = _balances[from].SUB55(value);
_balances[to] = _balances[to].ADD666(value);
emit TRANSFER418(from, to, value);
}
function _MINT600(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.ADD666(value);
_balances[account] = _balances[account].ADD666(value);
emit TRANSFER418(address(0), account, value);
}
function _BURN785(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.SUB55(value);
_balances[account] = _balances[account].SUB55(value);
emit TRANSFER418(account, address(0), value);
}
function _BURNFROM615(address account, uint256 value) internal { //inject NONSTANDARD NAMING
_allowed[account][msg.sender] = _allowed[account][msg.sender].SUB55(value);
_BURN785(account, value);
emit APPROVAL780(account, msg.sender, _allowed[account][msg.sender]);
}
}
contract ERC20Burnable is ERC20Pistachio {
bool private _burnableActive;
function BURN665(uint256 value) public WHENBURNABLEACTIVE644 { //inject NONSTANDARD NAMING
_BURN785(msg.sender, value);
}
function BURNFROM948(address from, uint256 value) public WHENBURNABLEACTIVE644 { //inject NONSTANDARD NAMING
_BURNFROM615(from, value);
}
function _SETBURNABLEACTIVE519(bool _active) internal { //inject NONSTANDARD NAMING
_burnableActive = _active;
}
modifier WHENBURNABLEACTIVE644() { //inject NONSTANDARD NAMING
require(_burnableActive);
_;
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function ADD666(Role storage role, address account) internal { //inject NONSTANDARD NAMING
require(account != address(0));
require(!HAS322(role, account));
role.bearer[account] = true;
}
function REMOVE231(Role storage role, address account) internal { //inject NONSTANDARD NAMING
require(account != address(0));
require(HAS322(role, account));
role.bearer[account] = false;
}
function HAS322(Role storage role, address account) internal view returns (bool) { //inject NONSTANDARD NAMING
require(account != address(0));
return role.bearer[account];
}
}
contract MinterRole {
using Roles for Roles.Role;
event MINTERADDED605(address indexed account); //inject NONSTANDARD NAMING
event MINTERREMOVED905(address indexed account); //inject NONSTANDARD NAMING
Roles.Role private _minters;
constructor () internal {
_ADDMINTER929(msg.sender);
}
modifier ONLYMINTER785() { //inject NONSTANDARD NAMING
require(ISMINTER455(msg.sender));
_;
}
function ISMINTER455(address account) public view returns (bool) { //inject NONSTANDARD NAMING
return _minters.HAS322(account);
}
function ADDMINTER562(address account) public ONLYMINTER785 { //inject NONSTANDARD NAMING
_ADDMINTER929(account);
}
function RENOUNCEMINTER297() public { //inject NONSTANDARD NAMING
_REMOVEMINTER917(msg.sender);
}
function _ADDMINTER929(address account) internal { //inject NONSTANDARD NAMING
_minters.ADD666(account);
emit MINTERADDED605(account);
}
function _REMOVEMINTER917(address account) internal { //inject NONSTANDARD NAMING
_minters.REMOVE231(account);
emit MINTERREMOVED905(account);
}
}
contract ERC20Mintable is ERC20Pistachio, MinterRole {
bool private _mintableActive;
function MINT525(address to, uint256 value) public ONLYMINTER785 WHENMINTABLEACTIVE702 returns (bool) { //inject NONSTANDARD NAMING
_MINT600(to, value);
return true;
}
function _SETMINTABLEACTIVE686(bool _active) internal { //inject NONSTANDARD NAMING
_mintableActive = _active;
}
modifier WHENMINTABLEACTIVE702() { //inject NONSTANDARD NAMING
require(_mintableActive);
_;
}
}
contract PauserRole {
using Roles for Roles.Role;
event PAUSERADDED252(address indexed account); //inject NONSTANDARD NAMING
event PAUSERREMOVED538(address indexed account); //inject NONSTANDARD NAMING
Roles.Role private _pausers;
constructor () internal {
_ADDPAUSER941(msg.sender);
}
modifier ONLYPAUSER672() { //inject NONSTANDARD NAMING
require(ISPAUSER604(msg.sender));
_;
}
function ISPAUSER604(address account) public view returns (bool) { //inject NONSTANDARD NAMING
return _pausers.HAS322(account);
}
function ADDPAUSER65(address account) public ONLYPAUSER672 { //inject NONSTANDARD NAMING
_ADDPAUSER941(account);
}
function RENOUNCEPAUSER647() public { //inject NONSTANDARD NAMING
_REMOVEPAUSER706(msg.sender);
}
function _ADDPAUSER941(address account) internal { //inject NONSTANDARD NAMING
_pausers.ADD666(account);
emit PAUSERADDED252(account);
}
function _REMOVEPAUSER706(address account) internal { //inject NONSTANDARD NAMING
_pausers.REMOVE231(account);
emit PAUSERREMOVED538(account);
}
}
contract Pausable is PauserRole {
event PAUSED114(address account); //inject NONSTANDARD NAMING
event UNPAUSED110(address account); //inject NONSTANDARD NAMING
bool private _pausableActive;
bool private _paused;
constructor () internal {
_paused = false;
}
function PAUSED723() public view returns (bool) { //inject NONSTANDARD NAMING
return _paused;
}
modifier WHENNOTPAUSED424() { //inject NONSTANDARD NAMING
require(!_paused);
_;
}
modifier WHENPAUSED745() { //inject NONSTANDARD NAMING
require(_paused);
_;
}
function PAUSE827() public ONLYPAUSER672 WHENNOTPAUSED424 WHENPAUSABLEACTIVE658 { //inject NONSTANDARD NAMING
_paused = true;
emit PAUSED114(msg.sender);
}
function UNPAUSE942() public ONLYPAUSER672 WHENPAUSED745 WHENPAUSABLEACTIVE658 { //inject NONSTANDARD NAMING
_paused = false;
emit UNPAUSED110(msg.sender);
}
function _SETPAUSABLEACTIVE337(bool _active) internal { //inject NONSTANDARD NAMING
_pausableActive = _active;
}
modifier WHENPAUSABLEACTIVE658() { //inject NONSTANDARD NAMING
require(_pausableActive);
_;
}
}
contract ERC20Chocolate is ERC20Pistachio, ERC20Burnable, ERC20Mintable, Pausable {
// maximum capital, if defined > 0
uint256 private _cap;
constructor (
address initialAccount, string memory _tokenSymbol, string memory _tokenName, uint256 initialBalance, uint256 cap,
bool _burnableOption, bool _mintableOption, bool _pausableOption
) public
ERC20Pistachio(initialAccount, _tokenSymbol, _tokenName, initialBalance) {
// we must add customer account as the first minter
ADDMINTER562(initialAccount);
// add customer as pauser
ADDPAUSER65(initialAccount);
if (cap > 0) {
_cap = cap; // maximum capitalization limited
} else {
_cap = 0; // unlimited capitalization
}
// activate or deactivate options
_SETBURNABLEACTIVE519(_burnableOption);
_SETMINTABLEACTIVE686(_mintableOption);
_SETPAUSABLEACTIVE337(_pausableOption);
}
function CAP794() public view returns (uint256) { //inject NONSTANDARD NAMING
return _cap;
}
function _MINT600(address account, uint256 value) internal { //inject NONSTANDARD NAMING
if (_cap > 0) {
require(TOTALSUPPLY304().ADD666(value) <= _cap);
}
super._MINT600(account, value);
}
function TRANSFER854(address to, uint256 value) public WHENNOTPAUSED424 returns (bool) { //inject NONSTANDARD NAMING
return super.TRANSFER854(to, value);
}
function TRANSFERFROM522(address from,address to, uint256 value) public WHENNOTPAUSED424 returns (bool) { //inject NONSTANDARD NAMING
return super.TRANSFERFROM522(from, to, value);
}
function APPROVE531(address spender, uint256 value) public WHENNOTPAUSED424 returns (bool) { //inject NONSTANDARD NAMING
return super.APPROVE531(spender, value);
}
function INCREASEALLOWANCE330(address spender, uint addedValue) public WHENNOTPAUSED424 returns (bool success) { //inject NONSTANDARD NAMING
return super.INCREASEALLOWANCE330(spender, addedValue);
}
function DECREASEALLOWANCE446(address spender, uint subtractedValue) public WHENNOTPAUSED424 returns (bool success) { //inject NONSTANDARD NAMING
return super.DECREASEALLOWANCE446(spender, subtractedValue);
}
}
contract ReentrancyGuard {
// counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
modifier NONREENTRANT377() { //inject NONSTANDARD NAMING
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER714(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN667(token, abi.encodeWithSelector(token.TRANSFER854.selector, to, value));
}
function SAFETRANSFERFROM672(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN667(token, abi.encodeWithSelector(token.TRANSFERFROM522.selector, from, to, value));
}
function SAFEAPPROVE372(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.ALLOWANCE123(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN667(token, abi.encodeWithSelector(token.APPROVE531.selector, spender, value));
}
function SAFEINCREASEALLOWANCE265(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE123(address(this), spender).ADD666(value);
CALLOPTIONALRETURN667(token, abi.encodeWithSelector(token.APPROVE531.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE998(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE123(address(this), spender).SUB55(value);
CALLOPTIONALRETURN667(token, abi.encodeWithSelector(token.APPROVE531.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN667(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).ISCONTRACT761(), "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 {
function ISCONTRACT761(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 TOPAYABLE851(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
}
contract Crowdsale is ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for ERC20Chocolate;
// The token being sold
ERC20Chocolate private _token;
// Address where funds are collected
address payable private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
event TOKENSPURCHASED287(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //inject NONSTANDARD NAMING
constructor (uint256 rate, address payable wallet, ERC20Chocolate token) public {
require(rate > 0, "Crowdsale: rate is 0");
require(wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(token) != address(0), "Crowdsale: token is the zero address");
_rate = rate;
_wallet = wallet;
_token = token;
}
function () external payable {
BUYTOKENS434(msg.sender);
}
function TOKEN293() public view returns (IERC20) { //inject NONSTANDARD NAMING
return _token;
}
function WALLET108() public view returns (address payable) { //inject NONSTANDARD NAMING
return _wallet;
}
function RATE426() public view returns (uint256) { //inject NONSTANDARD NAMING
return _rate;
}
function WEIRAISED13() public view returns (uint256) { //inject NONSTANDARD NAMING
return _weiRaised;
}
function BUYTOKENS434(address beneficiary) public NONREENTRANT377 payable { //inject NONSTANDARD NAMING
uint256 weiAmount = msg.value;
_PREVALIDATEPURCHASE289(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _GETTOKENAMOUNT276(weiAmount);
// update state
_weiRaised = _weiRaised.ADD666(weiAmount);
_PROCESSPURCHASE887(beneficiary, tokens);
emit TOKENSPURCHASED287(msg.sender, beneficiary, weiAmount, tokens);
_UPDATEPURCHASINGSTATE322(beneficiary, weiAmount);
_FORWARDFUNDS963();
_POSTVALIDATEPURCHASE368(beneficiary, weiAmount);
}
function _PREVALIDATEPURCHASE289(address beneficiary, uint256 weiAmount) internal view { //inject NONSTANDARD NAMING
require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
require(weiAmount != 0, "Crowdsale: weiAmount is 0");
}
function _POSTVALIDATEPURCHASE368(address beneficiary, uint256 weiAmount) internal view { //inject NONSTANDARD NAMING
// solhint-disable-previous-line no-empty-blocks
}
function _DELIVERTOKENS47(address beneficiary, uint256 tokenAmount) internal { //inject NONSTANDARD NAMING
_token.SAFETRANSFER714(beneficiary, tokenAmount);
}
function _PROCESSPURCHASE887(address beneficiary, uint256 tokenAmount) internal { //inject NONSTANDARD NAMING
_DELIVERTOKENS47(beneficiary, tokenAmount);
}
function _UPDATEPURCHASINGSTATE322(address beneficiary, uint256 weiAmount) internal { //inject NONSTANDARD NAMING
// solhint-disable-previous-line no-empty-blocks
}
function _GETTOKENAMOUNT276(uint256 weiAmount) internal view returns (uint256) { //inject NONSTANDARD NAMING
return weiAmount.MUL578(_rate);
}
function _FORWARDFUNDS963() internal { //inject NONSTANDARD NAMING
_wallet.transfer(msg.value);
}
}
contract MintedCrowdsale is Crowdsale {
function _DELIVERTOKENS47(address beneficiary, uint256 tokenAmount) internal { //inject NONSTANDARD NAMING
// Potentially dangerous assumption about the type of the token.
require(
ERC20Mintable(address(TOKEN293())).MINT525(beneficiary, tokenAmount),
"MintedCrowdsale: minting failed"
);
}
}
contract PausableCrowdsale is Crowdsale, Pausable {
function _PREVALIDATEPURCHASE289(address _beneficiary, uint256 _weiAmount) internal view WHENNOTPAUSED424 { //inject NONSTANDARD NAMING
return super._PREVALIDATEPURCHASE289(_beneficiary, _weiAmount);
}
}
contract CrowdsaleRaspberry is MintedCrowdsale, PausableCrowdsale {
constructor (uint256 rate, address payable wallet, ERC20Chocolate token, bool _isPausable) public
Crowdsale(rate, wallet, token) {
// solhint-disable-previous-line no-empty-blocks
_SETPAUSABLEACTIVE337(_isPausable);
}
} | inject NONSTANDARD NAMING | function ALLOWANCE123(address owner, address spender) external view returns (uint256); | 12,598,026 |
./full_match/8453/0x2dE89c7A9902291ac9c4f81a8121BE491E258aa9/sources/contracts/distribution/BASEGenesisRewardPool.sol | Update the given pool's TOMB allocation point. Can only be called by the owner. | function set(uint256 _pid, uint256 _allocPoint, uint256 depositFee) public onlyOperator {
require(depositFee < 500, "max deposit fee");
massUpdatePools();
PoolInfo storage pool = poolInfo[_pid];
if (pool.isStarted) {
totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(
_allocPoint
);
}
pool.allocPoint = _allocPoint;
pool.depositFee = depositFee;
}
| 11,537,646 |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.3.2 (utils/Counters.sol)
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 Counters {
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;
}
}
// File: @openzeppelin/contracts/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/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/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @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);
}
// File: @openzeppelin/contracts/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/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/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/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @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);
}
// File: @openzeppelin/contracts/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);
}
// File: @openzeppelin/contracts/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/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @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 {
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 = 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 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 {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @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();
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
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.
*
* 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() {
_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);
}
}
// File: @openzeppelin/contracts/interfaces/IERC2981.sol
pragma solidity ^0.8.0;
/**
* @dev Interface for the NFT Royalty Standard
*/
interface IERC2981 is IERC165 {
/**
* @dev 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 salePrice - 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 `salePrice`
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
/**Start of Barely Bears Contact */
//██████╗ █████╗ ██████╗ ███████╗██╗ ██╗ ██╗ ██████╗ ███████╗ █████╗ ██████╗ ███████╗
//██╔══██╗██╔══██╗██╔══██╗██╔════╝██║ ╚██╗ ██╔╝ ██╔══██╗██╔════╝██╔══██╗██╔══██╗██╔════╝
//██████╔╝███████║██████╔╝█████╗ ██║ ╚████╔╝ ██████╔╝█████╗ ███████║██████╔╝███████╗
//██╔══██╗██╔══██║██╔══██╗██╔══╝ ██║ ╚██╔╝ ██╔══██╗██╔══╝ ██╔══██║██╔══██╗╚════██║
//██████╔╝██║ ██║██║ ██║███████╗███████╗██║ ██████╔╝███████╗██║ ██║██║ ██║███████║
//╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝
//BarelyBears is the a generative NFT collection featuring 10,000 hand-painted bear portraits from a live human-bear
pragma solidity >=0.7.0 <0.9.0;
contract BarelyBears10k is ERC721Enumerable, Ownable {
using Strings for uint256;
string public baseURI;
string public baseExtension = ".json";
string public notRevealedUri;
uint256 public cost = 0.05 ether;
uint256 public maxSupply = 10000;
uint256 public maxWhitelistMintAmount = 4;
uint256 public maxMintAmount = 10;
uint256 public nftPerAddressLimit = 4;
uint256 private _tokenId = 0;
uint16 internal royalty = 1000; // base 10000, 10%
uint16 public constant BASE = 10000;
bool public paused = false;
bool public revealed = false;
bool public onlyWhitelisted = true;
address[] public whitelistedAddresses;
address public constant founderAddress = 0x9286c3d14C235Bf404a335a59F04fF806f6d6944;
address public constant projectAddress = 0x08269c0FA570C4Bc91cF054bFEdECe2A3CC9442b;
address public constant devAddress = 0x739A49E67D46A2f0f60217901CFd6a86E816Cc62;
address public constant artist1Address = 0x4ba4a533D9355BbF0cE56BAF9fe15E2cccc83132;
address public constant artist2Address = 0x82341fB007544721efa2e3E74fA7421888B10489;
mapping(address => uint256) public addressMintedBalance;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
string memory _initNotRevealedUri
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
setNotRevealedURI(_initNotRevealedUri);
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
struct FreeBearUser {
uint maxMint;
}
mapping (address => FreeBearUser ) wlUsers;
address[] public userAccounts;
function resetFreeBearUsers (address _address) public {
FreeBearUser storage wlUser = wlUsers[_address];
wlUser.maxMint = 0;
}
function getFreeBearUserAccount(address _address) view public returns (uint) {
return (wlUsers[_address].maxMint);
}
function normalMint(uint256 _mintAmount) public payable {
require(!paused, "the contract is paused");
uint256 supply = totalSupply();
require(_mintAmount > 0, "need to mint at least 1 NFT");
require(_mintAmount <= maxMintAmount, "max mint amount per session exceeded");
require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded");
if (msg.sender != owner()) {
require(msg.value >= cost * _mintAmount, "insufficient funds");
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
function freeMint() public payable {
require(!paused, "the contract is paused");
uint256 supply = totalSupply();
uint256 cost = 0;
uint256 _mintAmount = getFreeBearUserAccount(msg.sender);
require(_mintAmount > 0, "you are not entitled for a free bear");
require(_mintAmount <= maxMintAmount, "max mint amount per session exceeded");
require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded");
if (msg.sender != owner()) {
require(msg.value >= cost * _mintAmount, "insufficient funds");
}
for (uint256 i = 1; i <= _mintAmount; i++) {
addressMintedBalance[msg.sender]++;
_safeMint(msg.sender, supply + i);
}
resetFreeBearUsers(msg.sender);
}
function whitelistMint(uint256 _mintAmount) public payable {
require(!paused, "the contract is paused");
uint256 supply = totalSupply();
require(_mintAmount > 0, "need to mint at least 1 NFT");
require(_mintAmount <= maxWhitelistMintAmount, "cannot mint more than 4 NFT on whitelist");
require(_mintAmount <= maxMintAmount, "max mint amount per session exceeded");
require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded");
if (msg.sender != owner()) {
if(onlyWhitelisted == true) {
require(isWhitelisted(msg.sender), "user is not whitelisted");
uint256 ownerMintedCount = addressMintedBalance[msg.sender];
require(ownerMintedCount + _mintAmount <= nftPerAddressLimit, "max NFT per address exceeded");
}
require(msg.value >= cost * _mintAmount, "insufficient funds");
}
for (uint256 i = 1; i <= _mintAmount; i++) {
addressMintedBalance[msg.sender]++;
_safeMint(msg.sender, supply + i);
}
}
function isWhitelisted(address _user) public view returns (bool) {
for (uint i = 0; i < whitelistedAddresses.length; i++) {
if (whitelistedAddresses[i] == _user) {
return true;
}
}
return false;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if(revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
//only owner
function reveal() public onlyOwner {
revealed = true;
}
function setNftPerAddressLimit(uint256 _limit) public onlyOwner {
nftPerAddressLimit = _limit;
}
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setMaxWhitelistMintAmount(uint256 _newmaxWhitelistMintAmount) public onlyOwner {
maxWhitelistMintAmount = _newmaxWhitelistMintAmount;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner {
maxMintAmount = _newmaxMintAmount;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function setFreeBearUsers (address _address, uint _maxMint) public onlyOwner {
FreeBearUser storage wlUser = wlUsers[_address];
wlUser.maxMint = _maxMint;
}
function setOnlyWhitelisted(bool _state) public onlyOwner {
onlyWhitelisted = _state;
}
function whitelistUsers(address[] calldata _users) public onlyOwner {
delete whitelistedAddresses;
whitelistedAddresses = _users;
}
function withdrawAll() public onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0, "Insufficent balance");
_widthdraw(projectAddress, ((balance * 20) / 100));
_widthdraw(devAddress, ((balance * 10) / 100));
_widthdraw(artist1Address, ((balance * 10) / 100));
_widthdraw(artist2Address, ((balance * 10) / 100));
_widthdraw(founderAddress, address(this).balance);
}
function _widthdraw(address _address, uint256 _amount) private {
(bool success, ) = _address.call{ value: _amount }("");
require(success, "Failed to widthdraw Ether");
}
/// @notice Calculate the royalty payment
/// @param _salePrice the sale price of the token
function royaltyInfo(uint256, uint256 _salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
return (address(this), (_salePrice * royalty) / BASE);
}
/// @dev set the royalty
/// @param _royalty the royalty in base 10000, 500 = 5%
function setRoyalty(uint16 _royalty) public virtual onlyOwner {
require(_royalty >= 0 && _royalty <= 1000, 'Royalty must be between 0% and 10%.');
royalty = _royalty;
}
} | Calculate the royalty payment _salePrice the sale price of the token | function royaltyInfo(uint256, uint256 _salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
return (address(this), (_salePrice * royalty) / BASE);
}
| 13,934,875 |
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./interfaces/IAuthorizer.sol";
import "./interfaces/IWETH.sol";
import "./VaultAuthorization.sol";
import "./FlashLoans.sol";
import "./Swaps.sol";
/**
* @dev The `Vault` is Balancer V2's core contract. A single instance of it exists for the entire network, and it is the
* entity used to interact with Pools by Liquidity Providers who join and exit them, Traders who swap, and Asset
* Managers who withdraw and deposit tokens.
*
* The `Vault`'s source code is split among a number of sub-contracts, with the goal of improving readability and making
* understanding the system easier. Most sub-contracts have been marked as `abstract` to explicitly indicate that only
* the full `Vault` is meant to be deployed.
*
* Roughly speaking, these are the contents of each sub-contract:
*
* - `AssetManagers`: Pool token Asset Manager registry, and Asset Manager interactions.
* - `Fees`: set and compute protocol fees.
* - `FlashLoans`: flash loan transfers and fees.
* - `PoolBalances`: Pool joins and exits.
* - `PoolRegistry`: Pool registration, ID management, and basic queries.
* - `PoolTokens`: Pool token registration and registration, and balance queries.
* - `Swaps`: Pool swaps.
* - `UserBalance`: manage user balances (Internal Balance operations and external balance transfers)
* - `VaultAuthorization`: access control, relayers and signature validation.
*
* Additionally, the different Pool specializations are handled by the `GeneralPoolsBalance`,
* `MinimalSwapInfoPoolsBalance` and `TwoTokenPoolsBalance` sub-contracts, which in turn make use of the
* `BalanceAllocation` library.
*
* The most important goal of the `Vault` is to make token swaps use as little gas as possible. This is reflected in a
* multitude of design decisions, from minor things like the format used to store Pool IDs, to major features such as
* the different Pool specialization settings.
*
* Finally, the large number of tasks carried out by the Vault means its bytecode is very large, close to exceeding
* the contract size limit imposed by EIP 170 (https://eips.ethereum.org/EIPS/eip-170). Manual tuning of the source code
* was required to improve code generation and bring the bytecode size below this limit. This includes extensive
* utilization of `internal` functions (particularly inside modifiers), usage of named return arguments, dedicated
* storage access methods, dynamic revert reason generation, and usage of inline assembly, to name a few.
*/
contract Vault is VaultAuthorization, FlashLoans, Swaps {
constructor(
IAuthorizer authorizer,
IWETH weth,
uint256 pauseWindowDuration,
uint256 bufferPeriodDuration
) VaultAuthorization(authorizer) AssetHelpers(weth) TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration) {
// solhint-disable-previous-line no-empty-blocks
}
function setPaused(bool paused) external override nonReentrant authenticate {
_setPaused(paused);
}
// solhint-disable-next-line func-name-mixedcase
function WETH() external view override returns (IWETH) {
return _WETH();
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
interface IAuthorizer {
/**
* @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`.
*/
function canPerform(
bytes32 actionId,
address account,
address where
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../../lib/openzeppelin/IERC20.sol";
/**
* @dev Interface for the WETH token contract used internally for wrapping and unwrapping, to support
* sending and receiving ETH in joins, swaps, and internal balance deposits and withdrawals.
*/
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/helpers/BalancerErrors.sol";
import "../lib/helpers/Authentication.sol";
import "../lib/helpers/TemporarilyPausable.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/helpers/SignaturesValidator.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "./interfaces/IVault.sol";
import "./interfaces/IAuthorizer.sol";
/**
* @dev Manages access control of Vault permissioned functions by relying on the Authorizer and signature validation.
*
* Additionally handles relayer access and approval.
*/
abstract contract VaultAuthorization is
IVault,
ReentrancyGuard,
Authentication,
SignaturesValidator,
TemporarilyPausable
{
// Ideally, we'd store the type hashes as immutable state variables to avoid computing the hash at runtime, but
// unfortunately immutable variables cannot be used in assembly, so we just keep the precomputed hashes instead.
// _JOIN_TYPE_HASH = keccak256("JoinPool(bytes calldata,address sender,uint256 nonce,uint256 deadline)");
bytes32 private constant _JOIN_TYPE_HASH = 0x3f7b71252bd19113ff48c19c6e004a9bcfcca320a0d74d58e85877cbd7dcae58;
// _EXIT_TYPE_HASH = keccak256("ExitPool(bytes calldata,address sender,uint256 nonce,uint256 deadline)");
bytes32 private constant _EXIT_TYPE_HASH = 0x8bbc57f66ea936902f50a71ce12b92c43f3c5340bb40c27c4e90ab84eeae3353;
// _SWAP_TYPE_HASH = keccak256("Swap(bytes calldata,address sender,uint256 nonce,uint256 deadline)");
bytes32 private constant _SWAP_TYPE_HASH = 0xe192dcbc143b1e244ad73b813fd3c097b832ad260a157340b4e5e5beda067abe;
// _BATCH_SWAP_TYPE_HASH = keccak256("BatchSwap(bytes calldata,address sender,uint256 nonce,uint256 deadline)");
bytes32 private constant _BATCH_SWAP_TYPE_HASH = 0x9bfc43a4d98313c6766986ffd7c916c7481566d9f224c6819af0a53388aced3a;
// _SET_RELAYER_TYPE_HASH =
// keccak256("SetRelayerApproval(bytes calldata,address sender,uint256 nonce,uint256 deadline)");
bytes32
private constant _SET_RELAYER_TYPE_HASH = 0xa3f865aa351e51cfeb40f5178d1564bb629fe9030b83caf6361d1baaf5b90b5a;
IAuthorizer private _authorizer;
mapping(address => mapping(address => bool)) private _approvedRelayers;
/**
* @dev Reverts unless `user` is the caller, or the caller is approved by the Authorizer to call this function (that
* is, it is a relayer for that function), and either:
* a) `user` approved the caller as a relayer (via `setRelayerApproval`), or
* b) a valid signature from them was appended to the calldata.
*
* Should only be applied to external functions.
*/
modifier authenticateFor(address user) {
_authenticateFor(user);
_;
}
constructor(IAuthorizer authorizer)
// The Vault is a singleton, so it simply uses its own address to disambiguate action identifiers.
Authentication(bytes32(uint256(address(this))))
SignaturesValidator("Balancer V2 Vault")
{
_setAuthorizer(authorizer);
}
function setAuthorizer(IAuthorizer newAuthorizer) external override nonReentrant authenticate {
_setAuthorizer(newAuthorizer);
}
function _setAuthorizer(IAuthorizer newAuthorizer) private {
emit AuthorizerChanged(newAuthorizer);
_authorizer = newAuthorizer;
}
function getAuthorizer() external view override returns (IAuthorizer) {
return _authorizer;
}
function setRelayerApproval(
address sender,
address relayer,
bool approved
) external override nonReentrant whenNotPaused authenticateFor(sender) {
_approvedRelayers[sender][relayer] = approved;
emit RelayerApprovalChanged(relayer, sender, approved);
}
function hasApprovedRelayer(address user, address relayer) external view override returns (bool) {
return _hasApprovedRelayer(user, relayer);
}
/**
* @dev Reverts unless `user` is the caller, or the caller is approved by the Authorizer to call the entry point
* function (that is, it is a relayer for that function) and either:
* a) `user` approved the caller as a relayer (via `setRelayerApproval`), or
* b) a valid signature from them was appended to the calldata.
*/
function _authenticateFor(address user) internal {
if (msg.sender != user) {
// In this context, 'permission to call a function' means 'being a relayer for a function'.
_authenticateCaller();
// Being a relayer is not sufficient: `user` must have also approved the caller either via
// `setRelayerApproval`, or by providing a signature appended to the calldata.
if (!_hasApprovedRelayer(user, msg.sender)) {
_validateSignature(user, Errors.USER_DOESNT_ALLOW_RELAYER);
}
}
}
/**
* @dev Returns true if `user` approved `relayer` to act as a relayer for them.
*/
function _hasApprovedRelayer(address user, address relayer) internal view returns (bool) {
return _approvedRelayers[user][relayer];
}
function _canPerform(bytes32 actionId, address user) internal view override returns (bool) {
// Access control is delegated to the Authorizer.
return _authorizer.canPerform(actionId, user, address(this));
}
function _typeHash() internal pure override returns (bytes32 hash) {
// This is a simple switch-case statement, trivially written in Solidity by chaining else-if statements, but the
// assembly implementation results in much denser bytecode.
// solhint-disable-next-line no-inline-assembly
assembly {
// The function selector is located at the first 4 bytes of calldata. We copy the first full calldata
// 256 word, and then perform a logical shift to the right, moving the selector to the least significant
// 4 bytes.
let selector := shr(224, calldataload(0))
// With the selector in the least significant 4 bytes, we can use 4 byte literals with leading zeros,
// resulting in dense bytecode (PUSH4 opcodes).
switch selector
case 0xb95cac28 {
hash := _JOIN_TYPE_HASH
}
case 0x8bdb3913 {
hash := _EXIT_TYPE_HASH
}
case 0x52bbbe29 {
hash := _SWAP_TYPE_HASH
}
case 0x945bcec9 {
hash := _BATCH_SWAP_TYPE_HASH
}
case 0xfa6e671d {
hash := _SET_RELAYER_TYPE_HASH
}
default {
hash := 0x0000000000000000000000000000000000000000000000000000000000000000
}
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// This flash loan provider was based on the Aave protocol's open source
// implementation and terminology and interfaces are intentionally kept
// similar
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/helpers/BalancerErrors.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./Fees.sol";
import "./interfaces/IFlashLoanRecipient.sol";
/**
* @dev Handles Flash Loans through the Vault. Calls the `receiveFlashLoan` hook on the flash loan recipient
* contract, which implements the `IFlashLoanRecipient` interface.
*/
abstract contract FlashLoans is Fees, ReentrancyGuard, TemporarilyPausable {
using SafeERC20 for IERC20;
function flashLoan(
IFlashLoanRecipient recipient,
IERC20[] memory tokens,
uint256[] memory amounts,
bytes memory userData
) external override nonReentrant whenNotPaused {
InputHelpers.ensureInputLengthMatch(tokens.length, amounts.length);
uint256[] memory feeAmounts = new uint256[](tokens.length);
uint256[] memory preLoanBalances = new uint256[](tokens.length);
// Used to ensure `tokens` is sorted in ascending order, which ensures token uniqueness.
IERC20 previousToken = IERC20(0);
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
uint256 amount = amounts[i];
_require(token > previousToken, token == IERC20(0) ? Errors.ZERO_TOKEN : Errors.UNSORTED_TOKENS);
previousToken = token;
preLoanBalances[i] = token.balanceOf(address(this));
feeAmounts[i] = _calculateFlashLoanFeeAmount(amount);
_require(preLoanBalances[i] >= amount, Errors.INSUFFICIENT_FLASH_LOAN_BALANCE);
token.safeTransfer(address(recipient), amount);
}
recipient.receiveFlashLoan(tokens, amounts, feeAmounts, userData);
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
uint256 preLoanBalance = preLoanBalances[i];
// Checking for loan repayment first (without accounting for fees) makes for simpler debugging, and results
// in more accurate revert reasons if the flash loan protocol fee percentage is zero.
uint256 postLoanBalance = token.balanceOf(address(this));
_require(postLoanBalance >= preLoanBalance, Errors.INVALID_POST_LOAN_BALANCE);
// No need for checked arithmetic since we know the loan was fully repaid.
uint256 receivedFeeAmount = postLoanBalance - preLoanBalance;
_require(receivedFeeAmount >= feeAmounts[i], Errors.INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT);
_payFeeAmount(token, receivedFeeAmount);
emit FlashLoan(recipient, token, amounts[i], receivedFeeAmount);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/math/Math.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/helpers/InputHelpers.sol";
import "../lib/openzeppelin/EnumerableMap.sol";
import "../lib/openzeppelin/EnumerableSet.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeCast.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./PoolBalances.sol";
import "./interfaces/IPoolSwapStructs.sol";
import "./interfaces/IGeneralPool.sol";
import "./interfaces/IMinimalSwapInfoPool.sol";
import "./balances/BalanceAllocation.sol";
/**
* Implements the Vault's high-level swap functionality.
*
* Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. They need not trust the Pool
* contracts to do this: all security checks are made by the Vault.
*
* The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
* In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
* and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
* More complex swaps, such as one 'token in' to multiple tokens out can be achieved by batching together
* individual swaps.
*/
abstract contract Swaps is ReentrancyGuard, PoolBalances {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableMap for EnumerableMap.IERC20ToBytes32Map;
using Math for int256;
using Math for uint256;
using SafeCast for uint256;
using BalanceAllocation for bytes32;
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
)
external
payable
override
nonReentrant
whenNotPaused
authenticateFor(funds.sender)
returns (uint256 amountCalculated)
{
// The deadline is timestamp-based: it should not be relied upon for sub-minute accuracy.
// solhint-disable-next-line not-rely-on-time
_require(block.timestamp <= deadline, Errors.SWAP_DEADLINE);
// This revert reason is for consistency with `batchSwap`: an equivalent `swap` performed using that function
// would result in this error.
_require(singleSwap.amount > 0, Errors.UNKNOWN_AMOUNT_IN_FIRST_SWAP);
IERC20 tokenIn = _translateToIERC20(singleSwap.assetIn);
IERC20 tokenOut = _translateToIERC20(singleSwap.assetOut);
_require(tokenIn != tokenOut, Errors.CANNOT_SWAP_SAME_TOKEN);
// Initializing each struct field one-by-one uses less gas than setting all at once.
IPoolSwapStructs.SwapRequest memory poolRequest;
poolRequest.poolId = singleSwap.poolId;
poolRequest.kind = singleSwap.kind;
poolRequest.tokenIn = tokenIn;
poolRequest.tokenOut = tokenOut;
poolRequest.amount = singleSwap.amount;
poolRequest.userData = singleSwap.userData;
poolRequest.from = funds.sender;
poolRequest.to = funds.recipient;
// The lastChangeBlock field is left uninitialized.
uint256 amountIn;
uint256 amountOut;
(amountCalculated, amountIn, amountOut) = _swapWithPool(poolRequest);
_require(singleSwap.kind == SwapKind.GIVEN_IN ? amountOut >= limit : amountIn <= limit, Errors.SWAP_LIMIT);
_receiveAsset(singleSwap.assetIn, amountIn, funds.sender, funds.fromInternalBalance);
_sendAsset(singleSwap.assetOut, amountOut, funds.recipient, funds.toInternalBalance);
// If the asset in is ETH, then `amountIn` ETH was wrapped into WETH.
_handleRemainingEth(_isETH(singleSwap.assetIn) ? amountIn : 0);
}
function batchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
int256[] memory limits,
uint256 deadline
)
external
payable
override
nonReentrant
whenNotPaused
authenticateFor(funds.sender)
returns (int256[] memory assetDeltas)
{
// The deadline is timestamp-based: it should not be relied upon for sub-minute accuracy.
// solhint-disable-next-line not-rely-on-time
_require(block.timestamp <= deadline, Errors.SWAP_DEADLINE);
InputHelpers.ensureInputLengthMatch(assets.length, limits.length);
// Perform the swaps, updating the Pool token balances and computing the net Vault asset deltas.
assetDeltas = _swapWithPools(swaps, assets, funds, kind);
// Process asset deltas, by either transferring assets from the sender (for positive deltas) or to the recipient
// (for negative deltas).
uint256 wrappedEth = 0;
for (uint256 i = 0; i < assets.length; ++i) {
IAsset asset = assets[i];
int256 delta = assetDeltas[i];
_require(delta <= limits[i], Errors.SWAP_LIMIT);
if (delta > 0) {
uint256 toReceive = uint256(delta);
_receiveAsset(asset, toReceive, funds.sender, funds.fromInternalBalance);
if (_isETH(asset)) {
wrappedEth = wrappedEth.add(toReceive);
}
} else if (delta < 0) {
uint256 toSend = uint256(-delta);
_sendAsset(asset, toSend, funds.recipient, funds.toInternalBalance);
}
}
// Handle any used and remaining ETH.
_handleRemainingEth(wrappedEth);
}
// For `_swapWithPools` to handle both 'given in' and 'given out' swaps, it internally tracks the 'given' amount
// (supplied by the caller), and the 'calculated' amount (returned by the Pool in response to the swap request).
/**
* @dev Given the two swap tokens and the swap kind, returns which one is the 'given' token (the token whose
* amount is supplied by the caller).
*/
function _tokenGiven(
SwapKind kind,
IERC20 tokenIn,
IERC20 tokenOut
) private pure returns (IERC20) {
return kind == SwapKind.GIVEN_IN ? tokenIn : tokenOut;
}
/**
* @dev Given the two swap tokens and the swap kind, returns which one is the 'calculated' token (the token whose
* amount is calculated by the Pool).
*/
function _tokenCalculated(
SwapKind kind,
IERC20 tokenIn,
IERC20 tokenOut
) private pure returns (IERC20) {
return kind == SwapKind.GIVEN_IN ? tokenOut : tokenIn;
}
/**
* @dev Returns an ordered pair (amountIn, amountOut) given the 'given' and 'calculated' amounts, and the swap kind.
*/
function _getAmounts(
SwapKind kind,
uint256 amountGiven,
uint256 amountCalculated
) private pure returns (uint256 amountIn, uint256 amountOut) {
if (kind == SwapKind.GIVEN_IN) {
(amountIn, amountOut) = (amountGiven, amountCalculated);
} else {
// SwapKind.GIVEN_OUT
(amountIn, amountOut) = (amountCalculated, amountGiven);
}
}
/**
* @dev Performs all `swaps`, calling swap hooks on the Pool contracts and updating their balances. Does not cause
* any transfer of tokens - instead it returns the net Vault token deltas: positive if the Vault should receive
* tokens, and negative if it should send them.
*/
function _swapWithPools(
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
SwapKind kind
) private returns (int256[] memory assetDeltas) {
assetDeltas = new int256[](assets.length);
// These variables could be declared inside the loop, but that causes the compiler to allocate memory on each
// loop iteration, increasing gas costs.
BatchSwapStep memory batchSwapStep;
IPoolSwapStructs.SwapRequest memory poolRequest;
// These store data about the previous swap here to implement multihop logic across swaps.
IERC20 previousTokenCalculated;
uint256 previousAmountCalculated;
for (uint256 i = 0; i < swaps.length; ++i) {
batchSwapStep = swaps[i];
bool withinBounds = batchSwapStep.assetInIndex < assets.length &&
batchSwapStep.assetOutIndex < assets.length;
_require(withinBounds, Errors.OUT_OF_BOUNDS);
IERC20 tokenIn = _translateToIERC20(assets[batchSwapStep.assetInIndex]);
IERC20 tokenOut = _translateToIERC20(assets[batchSwapStep.assetOutIndex]);
_require(tokenIn != tokenOut, Errors.CANNOT_SWAP_SAME_TOKEN);
// Sentinel value for multihop logic
if (batchSwapStep.amount == 0) {
// When the amount given is zero, we use the calculated amount for the previous swap, as long as the
// current swap's given token is the previous calculated token. This makes it possible to swap a
// given amount of token A for token B, and then use the resulting token B amount to swap for token C.
_require(i > 0, Errors.UNKNOWN_AMOUNT_IN_FIRST_SWAP);
bool usingPreviousToken = previousTokenCalculated == _tokenGiven(kind, tokenIn, tokenOut);
_require(usingPreviousToken, Errors.MALCONSTRUCTED_MULTIHOP_SWAP);
batchSwapStep.amount = previousAmountCalculated;
}
// Initializing each struct field one-by-one uses less gas than setting all at once
poolRequest.poolId = batchSwapStep.poolId;
poolRequest.kind = kind;
poolRequest.tokenIn = tokenIn;
poolRequest.tokenOut = tokenOut;
poolRequest.amount = batchSwapStep.amount;
poolRequest.userData = batchSwapStep.userData;
poolRequest.from = funds.sender;
poolRequest.to = funds.recipient;
// The lastChangeBlock field is left uninitialized
uint256 amountIn;
uint256 amountOut;
(previousAmountCalculated, amountIn, amountOut) = _swapWithPool(poolRequest);
previousTokenCalculated = _tokenCalculated(kind, tokenIn, tokenOut);
// Accumulate Vault deltas across swaps
assetDeltas[batchSwapStep.assetInIndex] = assetDeltas[batchSwapStep.assetInIndex].add(amountIn.toInt256());
assetDeltas[batchSwapStep.assetOutIndex] = assetDeltas[batchSwapStep.assetOutIndex].sub(
amountOut.toInt256()
);
}
}
/**
* @dev Performs a swap according to the parameters specified in `request`, calling the Pool's contract hook and
* updating the Pool's balance.
*
* Returns the amount of tokens going into or out of the Vault as a result of this swap, depending on the swap kind.
*/
function _swapWithPool(IPoolSwapStructs.SwapRequest memory request)
private
returns (
uint256 amountCalculated,
uint256 amountIn,
uint256 amountOut
)
{
// Get the calculated amount from the Pool and update its balances
address pool = _getPoolAddress(request.poolId);
PoolSpecialization specialization = _getPoolSpecialization(request.poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
amountCalculated = _processTwoTokenPoolSwapRequest(request, IMinimalSwapInfoPool(pool));
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
amountCalculated = _processMinimalSwapInfoPoolSwapRequest(request, IMinimalSwapInfoPool(pool));
} else {
// PoolSpecialization.GENERAL
amountCalculated = _processGeneralPoolSwapRequest(request, IGeneralPool(pool));
}
(amountIn, amountOut) = _getAmounts(request.kind, request.amount, amountCalculated);
emit Swap(request.poolId, request.tokenIn, request.tokenOut, amountIn, amountOut);
}
function _processTwoTokenPoolSwapRequest(IPoolSwapStructs.SwapRequest memory request, IMinimalSwapInfoPool pool)
private
returns (uint256 amountCalculated)
{
// For gas efficiency reasons, this function uses low-level knowledge of how Two Token Pool balances are
// stored internally, instead of using getters and setters for all operations.
(
bytes32 tokenABalance,
bytes32 tokenBBalance,
TwoTokenPoolBalances storage poolBalances
) = _getTwoTokenPoolSharedBalances(request.poolId, request.tokenIn, request.tokenOut);
// We have the two Pool balances, but we don't know which one is 'token in' or 'token out'.
bytes32 tokenInBalance;
bytes32 tokenOutBalance;
// In Two Token Pools, token A has a smaller address than token B
if (request.tokenIn < request.tokenOut) {
// in is A, out is B
tokenInBalance = tokenABalance;
tokenOutBalance = tokenBBalance;
} else {
// in is B, out is A
tokenOutBalance = tokenABalance;
tokenInBalance = tokenBBalance;
}
// Perform the swap request and compute the new balances for 'token in' and 'token out' after the swap
(tokenInBalance, tokenOutBalance, amountCalculated) = _callMinimalSwapInfoPoolOnSwapHook(
request,
pool,
tokenInBalance,
tokenOutBalance
);
// We check the token ordering again to create the new shared cash packed struct
poolBalances.sharedCash = request.tokenIn < request.tokenOut
? BalanceAllocation.toSharedCash(tokenInBalance, tokenOutBalance) // in is A, out is B
: BalanceAllocation.toSharedCash(tokenOutBalance, tokenInBalance); // in is B, out is A
}
function _processMinimalSwapInfoPoolSwapRequest(
IPoolSwapStructs.SwapRequest memory request,
IMinimalSwapInfoPool pool
) private returns (uint256 amountCalculated) {
bytes32 tokenInBalance = _getMinimalSwapInfoPoolBalance(request.poolId, request.tokenIn);
bytes32 tokenOutBalance = _getMinimalSwapInfoPoolBalance(request.poolId, request.tokenOut);
// Perform the swap request and compute the new balances for 'token in' and 'token out' after the swap
(tokenInBalance, tokenOutBalance, amountCalculated) = _callMinimalSwapInfoPoolOnSwapHook(
request,
pool,
tokenInBalance,
tokenOutBalance
);
_minimalSwapInfoPoolsBalances[request.poolId][request.tokenIn] = tokenInBalance;
_minimalSwapInfoPoolsBalances[request.poolId][request.tokenOut] = tokenOutBalance;
}
/**
* @dev Calls the onSwap hook for a Pool that implements IMinimalSwapInfoPool: both Minimal Swap Info and Two Token
* Pools do this.
*/
function _callMinimalSwapInfoPoolOnSwapHook(
IPoolSwapStructs.SwapRequest memory request,
IMinimalSwapInfoPool pool,
bytes32 tokenInBalance,
bytes32 tokenOutBalance
)
internal
returns (
bytes32 newTokenInBalance,
bytes32 newTokenOutBalance,
uint256 amountCalculated
)
{
uint256 tokenInTotal = tokenInBalance.total();
uint256 tokenOutTotal = tokenOutBalance.total();
request.lastChangeBlock = Math.max(tokenInBalance.lastChangeBlock(), tokenOutBalance.lastChangeBlock());
// Perform the swap request callback, and compute the new balances for 'token in' and 'token out' after the swap
amountCalculated = pool.onSwap(request, tokenInTotal, tokenOutTotal);
(uint256 amountIn, uint256 amountOut) = _getAmounts(request.kind, request.amount, amountCalculated);
newTokenInBalance = tokenInBalance.increaseCash(amountIn);
newTokenOutBalance = tokenOutBalance.decreaseCash(amountOut);
}
function _processGeneralPoolSwapRequest(IPoolSwapStructs.SwapRequest memory request, IGeneralPool pool)
private
returns (uint256 amountCalculated)
{
bytes32 tokenInBalance;
bytes32 tokenOutBalance;
// We access both token indexes without checking existence, because we will do it manually immediately after.
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[request.poolId];
uint256 indexIn = poolBalances.unchecked_indexOf(request.tokenIn);
uint256 indexOut = poolBalances.unchecked_indexOf(request.tokenOut);
if (indexIn == 0 || indexOut == 0) {
// The tokens might not be registered because the Pool itself is not registered. We check this to provide a
// more accurate revert reason.
_ensureRegisteredPool(request.poolId);
_revert(Errors.TOKEN_NOT_REGISTERED);
}
// EnumerableMap stores indices *plus one* to use the zero index as a sentinel value - because these are valid,
// we can undo this.
indexIn -= 1;
indexOut -= 1;
uint256 tokenAmount = poolBalances.length();
uint256[] memory currentBalances = new uint256[](tokenAmount);
request.lastChangeBlock = 0;
for (uint256 i = 0; i < tokenAmount; i++) {
// Because the iteration is bounded by `tokenAmount`, and no tokens are registered or deregistered here, we
// know `i` is a valid token index and can use `unchecked_valueAt` to save storage reads.
bytes32 balance = poolBalances.unchecked_valueAt(i);
currentBalances[i] = balance.total();
request.lastChangeBlock = Math.max(request.lastChangeBlock, balance.lastChangeBlock());
if (i == indexIn) {
tokenInBalance = balance;
} else if (i == indexOut) {
tokenOutBalance = balance;
}
}
// Perform the swap request callback and compute the new balances for 'token in' and 'token out' after the swap
amountCalculated = pool.onSwap(request, currentBalances, indexIn, indexOut);
(uint256 amountIn, uint256 amountOut) = _getAmounts(request.kind, request.amount, amountCalculated);
tokenInBalance = tokenInBalance.increaseCash(amountIn);
tokenOutBalance = tokenOutBalance.decreaseCash(amountOut);
// Because no tokens were registered or deregistered between now or when we retrieved the indexes for
// 'token in' and 'token out', we can use `unchecked_setAt` to save storage reads.
poolBalances.unchecked_setAt(indexIn, tokenInBalance);
poolBalances.unchecked_setAt(indexOut, tokenOutBalance);
}
// This function is not marked as `nonReentrant` because the underlying mechanism relies on reentrancy
function queryBatchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds
) external override returns (int256[] memory) {
// In order to accurately 'simulate' swaps, this function actually does perform the swaps, including calling the
// Pool hooks and updating balances in storage. However, once it computes the final Vault Deltas, it
// reverts unconditionally, returning this array as the revert data.
//
// By wrapping this reverting call, we can decode the deltas 'returned' and return them as a normal Solidity
// function would. The only caveat is the function becomes non-view, but off-chain clients can still call it
// via eth_call to get the expected result.
//
// This technique was inspired by the work from the Gnosis team in the Gnosis Safe contract:
// https://github.com/gnosis/safe-contracts/blob/v1.2.0/contracts/GnosisSafe.sol#L265
//
// Most of this function is implemented using inline assembly, as the actual work it needs to do is not
// significant, and Solidity is not particularly well-suited to generate this behavior, resulting in a large
// amount of generated bytecode.
if (msg.sender != address(this)) {
// We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of
// the preceding if statement will be executed instead.
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(msg.data);
// solhint-disable-next-line no-inline-assembly
assembly {
// This call should always revert to decode the actual asset deltas from the revert reason
switch success
case 0 {
// Note we are manually writing the memory slot 0. We can safely overwrite whatever is
// stored there as we take full control of the execution and then immediately return.
// We copy the first 4 bytes to check if it matches with the expected signature, otherwise
// there was another revert reason and we should forward it.
returndatacopy(0, 0, 0x04)
let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000)
// If the first 4 bytes don't match with the expected signature, we forward the revert reason.
if eq(eq(error, 0xfa61cc1200000000000000000000000000000000000000000000000000000000), 0) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
// The returndata contains the signature, followed by the raw memory representation of an array:
// length + data. We need to return an ABI-encoded representation of this array.
// An ABI-encoded array contains an additional field when compared to its raw memory
// representation: an offset to the location of the length. The offset itself is 32 bytes long,
// so the smallest value we can use is 32 for the data to be located immediately after it.
mstore(0, 32)
// We now copy the raw memory array from returndata into memory. Since the offset takes up 32
// bytes, we start copying at address 0x20. We also get rid of the error signature, which takes
// the first four bytes of returndata.
let size := sub(returndatasize(), 0x04)
returndatacopy(0x20, 0x04, size)
// We finally return the ABI-encoded array, which has a total length equal to that of the array
// (returndata), plus the 32 bytes for the offset.
return(0, add(size, 32))
}
default {
// This call should always revert, but we fail nonetheless if that didn't happen
invalid()
}
}
} else {
int256[] memory deltas = _swapWithPools(swaps, assets, funds, kind);
// solhint-disable-next-line no-inline-assembly
assembly {
// We will return a raw representation of the array in memory, which is composed of a 32 byte length,
// followed by the 32 byte int256 values. Because revert expects a size in bytes, we multiply the array
// length (stored at `deltas`) by 32.
let size := mul(mload(deltas), 32)
// We send one extra value for the error signature "QueryError(int256[])" which is 0xfa61cc12.
// We store it in the previous slot to the `deltas` array. We know there will be at least one available
// slot due to how the memory scratch space works.
// We can safely overwrite whatever is stored in this slot as we will revert immediately after that.
mstore(sub(deltas, 0x20), 0x00000000000000000000000000000000000000000000000000000000fa61cc12)
let start := sub(deltas, 0x04)
// When copying from `deltas` into returndata, we copy an additional 36 bytes to also return the array's
// length and the error signature.
revert(start, add(size, 36))
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
// solhint-disable
/**
* @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are
* supported.
*/
function _require(bool condition, uint256 errorCode) pure {
if (!condition) _revert(errorCode);
}
/**
* @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported.
*/
function _revert(uint256 errorCode) pure {
// We're going to dynamically create a revert string based on the error code, with the following format:
// 'BAL#{errorCode}'
// where the code is left-padded with zeroes to three digits (so they range from 000 to 999).
//
// We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a
// number (8 to 16 bits) than the individual string characters.
//
// The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a
// much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a
// safe place to rely on it without worrying about how its usage might affect e.g. memory contents.
assembly {
// First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999
// range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for
// the '0' character.
let units := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let tenths := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let hundreds := add(mod(errorCode, 10), 0x30)
// With the individual characters, we can now construct the full string. The "BAL#" part is a known constant
// (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the
// characters to it, each shifted by a multiple of 8.
// The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits
// per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte
// array).
let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds))))
// We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded
// message will have the following layout:
// [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ]
// The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We
// also write zeroes to the next 28 bytes of memory, but those are about to be overwritten.
mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
// Next is the offset to the location of the string, which will be placed immediately after (20 bytes away).
mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020)
// The string length is fixed: 7 characters.
mstore(0x24, 7)
// Finally, the string itself is stored.
mstore(0x44, revertReason)
// Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of
// the encoded message is therefore 4 + 32 + 32 + 32 = 100.
revert(0, 100)
}
}
library Errors {
// Math
uint256 internal constant ADD_OVERFLOW = 0;
uint256 internal constant SUB_OVERFLOW = 1;
uint256 internal constant SUB_UNDERFLOW = 2;
uint256 internal constant MUL_OVERFLOW = 3;
uint256 internal constant ZERO_DIVISION = 4;
uint256 internal constant DIV_INTERNAL = 5;
uint256 internal constant X_OUT_OF_BOUNDS = 6;
uint256 internal constant Y_OUT_OF_BOUNDS = 7;
uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8;
uint256 internal constant INVALID_EXPONENT = 9;
// Input
uint256 internal constant OUT_OF_BOUNDS = 100;
uint256 internal constant UNSORTED_ARRAY = 101;
uint256 internal constant UNSORTED_TOKENS = 102;
uint256 internal constant INPUT_LENGTH_MISMATCH = 103;
uint256 internal constant ZERO_TOKEN = 104;
// Shared pools
uint256 internal constant MIN_TOKENS = 200;
uint256 internal constant MAX_TOKENS = 201;
uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202;
uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203;
uint256 internal constant MINIMUM_BPT = 204;
uint256 internal constant CALLER_NOT_VAULT = 205;
uint256 internal constant UNINITIALIZED = 206;
uint256 internal constant BPT_IN_MAX_AMOUNT = 207;
uint256 internal constant BPT_OUT_MIN_AMOUNT = 208;
uint256 internal constant EXPIRED_PERMIT = 209;
// Pools
uint256 internal constant MIN_AMP = 300;
uint256 internal constant MAX_AMP = 301;
uint256 internal constant MIN_WEIGHT = 302;
uint256 internal constant MAX_STABLE_TOKENS = 303;
uint256 internal constant MAX_IN_RATIO = 304;
uint256 internal constant MAX_OUT_RATIO = 305;
uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306;
uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307;
uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308;
uint256 internal constant INVALID_TOKEN = 309;
uint256 internal constant UNHANDLED_JOIN_KIND = 310;
uint256 internal constant ZERO_INVARIANT = 311;
// Lib
uint256 internal constant REENTRANCY = 400;
uint256 internal constant SENDER_NOT_ALLOWED = 401;
uint256 internal constant PAUSED = 402;
uint256 internal constant PAUSE_WINDOW_EXPIRED = 403;
uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404;
uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405;
uint256 internal constant INSUFFICIENT_BALANCE = 406;
uint256 internal constant INSUFFICIENT_ALLOWANCE = 407;
uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408;
uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409;
uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410;
uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411;
uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412;
uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414;
uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416;
uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417;
uint256 internal constant SAFE_ERC20_CALL_FAILED = 418;
uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419;
uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420;
uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421;
uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422;
uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423;
uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424;
uint256 internal constant BUFFER_PERIOD_EXPIRED = 425;
// Vault
uint256 internal constant INVALID_POOL_ID = 500;
uint256 internal constant CALLER_NOT_POOL = 501;
uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502;
uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503;
uint256 internal constant INVALID_SIGNATURE = 504;
uint256 internal constant EXIT_BELOW_MIN = 505;
uint256 internal constant JOIN_ABOVE_MAX = 506;
uint256 internal constant SWAP_LIMIT = 507;
uint256 internal constant SWAP_DEADLINE = 508;
uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509;
uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510;
uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511;
uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512;
uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513;
uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514;
uint256 internal constant INVALID_POST_LOAN_BALANCE = 515;
uint256 internal constant INSUFFICIENT_ETH = 516;
uint256 internal constant UNALLOCATED_ETH = 517;
uint256 internal constant ETH_TRANSFER = 518;
uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519;
uint256 internal constant TOKENS_MISMATCH = 520;
uint256 internal constant TOKEN_NOT_REGISTERED = 521;
uint256 internal constant TOKEN_ALREADY_REGISTERED = 522;
uint256 internal constant TOKENS_ALREADY_SET = 523;
uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524;
uint256 internal constant NONZERO_TOKEN_BALANCE = 525;
uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526;
uint256 internal constant POOL_NO_TOKENS = 527;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528;
// Fees
uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600;
uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./BalancerErrors.sol";
import "./IAuthentication.sol";
/**
* @dev Building block for performing access control on external functions.
*
* This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied
* to external functions to only make them callable by authorized accounts.
*
* Derived contracts must implement the `_canPerform` function, which holds the actual access control logic.
*/
abstract contract Authentication is IAuthentication {
bytes32 private immutable _actionIdDisambiguator;
/**
* @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in
* multi contract systems.
*
* There are two main uses for it:
* - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers
* unique. The contract's own address is a good option.
* - if the contract belongs to a family that shares action identifiers for the same functions, an identifier
* shared by the entire family (and no other contract) should be used instead.
*/
constructor(bytes32 actionIdDisambiguator) {
_actionIdDisambiguator = actionIdDisambiguator;
}
/**
* @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions.
*/
modifier authenticate() {
_authenticateCaller();
_;
}
/**
* @dev Reverts unless the caller is allowed to call the entry point function.
*/
function _authenticateCaller() internal view {
bytes32 actionId = getActionId(msg.sig);
_require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED);
}
function getActionId(bytes4 selector) public view override returns (bytes32) {
// Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the
// function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of
// multiple contracts.
return keccak256(abi.encodePacked(_actionIdDisambiguator, selector));
}
function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./BalancerErrors.sol";
import "./ITemporarilyPausable.sol";
/**
* @dev Allows for a contract to be paused during an initial period after deployment, disabling functionality. Can be
* used as an emergency switch in case a security vulnerability or threat is identified.
*
* The contract can only be paused during the Pause Window, a period that starts at deployment. It can also be
* unpaused and repaused any number of times during this period. This is intended to serve as a safety measure: it lets
* system managers react quickly to potentially dangerous situations, knowing that this action is reversible if careful
* analysis later determines there was a false alarm.
*
* If the contract is paused when the Pause Window finishes, it will remain in the paused state through an additional
* Buffer Period, after which it will be automatically unpaused forever. This is to ensure there is always enough time
* to react to an emergency, even if the threat is discovered shortly before the Pause Window expires.
*
* Note that since the contract can only be paused within the Pause Window, unpausing during the Buffer Period is
* irreversible.
*/
abstract contract TemporarilyPausable is ITemporarilyPausable {
// The Pause Window and Buffer Period are timestamp-based: they should not be relied upon for sub-minute accuracy.
// solhint-disable not-rely-on-time
uint256 private constant _MAX_PAUSE_WINDOW_DURATION = 90 days;
uint256 private constant _MAX_BUFFER_PERIOD_DURATION = 30 days;
uint256 private immutable _pauseWindowEndTime;
uint256 private immutable _bufferPeriodEndTime;
bool private _paused;
constructor(uint256 pauseWindowDuration, uint256 bufferPeriodDuration) {
_require(pauseWindowDuration <= _MAX_PAUSE_WINDOW_DURATION, Errors.MAX_PAUSE_WINDOW_DURATION);
_require(bufferPeriodDuration <= _MAX_BUFFER_PERIOD_DURATION, Errors.MAX_BUFFER_PERIOD_DURATION);
uint256 pauseWindowEndTime = block.timestamp + pauseWindowDuration;
_pauseWindowEndTime = pauseWindowEndTime;
_bufferPeriodEndTime = pauseWindowEndTime + bufferPeriodDuration;
}
/**
* @dev Reverts if the contract is paused.
*/
modifier whenNotPaused() {
_ensureNotPaused();
_;
}
/**
* @dev Returns the current contract pause status, as well as the end times of the Pause Window and Buffer
* Period.
*/
function getPausedState()
external
view
override
returns (
bool paused,
uint256 pauseWindowEndTime,
uint256 bufferPeriodEndTime
)
{
paused = !_isNotPaused();
pauseWindowEndTime = _getPauseWindowEndTime();
bufferPeriodEndTime = _getBufferPeriodEndTime();
}
/**
* @dev Sets the pause state to `paused`. The contract can only be paused until the end of the Pause Window, and
* unpaused until the end of the Buffer Period.
*
* Once the Buffer Period expires, this function reverts unconditionally.
*/
function _setPaused(bool paused) internal {
if (paused) {
_require(block.timestamp < _getPauseWindowEndTime(), Errors.PAUSE_WINDOW_EXPIRED);
} else {
_require(block.timestamp < _getBufferPeriodEndTime(), Errors.BUFFER_PERIOD_EXPIRED);
}
_paused = paused;
emit PausedStateChanged(paused);
}
/**
* @dev Reverts if the contract is paused.
*/
function _ensureNotPaused() internal view {
_require(_isNotPaused(), Errors.PAUSED);
}
/**
* @dev Returns true if the contract is unpaused.
*
* Once the Buffer Period expires, the gas cost of calling this function is reduced dramatically, as storage is no
* longer accessed.
*/
function _isNotPaused() internal view returns (bool) {
// After the Buffer Period, the (inexpensive) timestamp check short-circuits the storage access.
return block.timestamp > _getBufferPeriodEndTime() || !_paused;
}
// These getters lead to reduced bytecode size by inlining the immutable variables in a single place.
function _getPauseWindowEndTime() private view returns (uint256) {
return _pauseWindowEndTime;
}
function _getBufferPeriodEndTime() private view returns (uint256) {
return _bufferPeriodEndTime;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./BalancerErrors.sol";
import "./ISignaturesValidator.sol";
import "../openzeppelin/EIP712.sol";
/**
* @dev Utility for signing Solidity function calls.
*
* This contract relies on the fact that Solidity contracts can be called with extra calldata, and enables
* meta-transaction schemes by appending an EIP712 signature of the original calldata at the end.
*
* Derived contracts must implement the `_typeHash` function to map function selectors to EIP712 structs.
*/
abstract contract SignaturesValidator is ISignaturesValidator, EIP712 {
// The appended data consists of a deadline, plus the [v,r,s] signature. For simplicity, we use a full 256 bit slot
// for each of these values, even if 'v' is typically an 8 bit value.
uint256 internal constant _EXTRA_CALLDATA_LENGTH = 4 * 32;
// Replay attack prevention for each user.
mapping(address => uint256) internal _nextNonce;
constructor(string memory name) EIP712(name, "1") {
// solhint-disable-previous-line no-empty-blocks
}
function getDomainSeparator() external view override returns (bytes32) {
return _domainSeparatorV4();
}
function getNextNonce(address user) external view override returns (uint256) {
return _nextNonce[user];
}
/**
* @dev Reverts with `errorCode` unless a valid signature for `user` was appended to the calldata.
*/
function _validateSignature(address user, uint256 errorCode) internal {
uint256 nextNonce = _nextNonce[user]++;
_require(_isSignatureValid(user, nextNonce), errorCode);
}
function _isSignatureValid(address user, uint256 nonce) private view returns (bool) {
uint256 deadline = _deadline();
// The deadline is timestamp-based: it should not be relied upon for sub-minute accuracy.
// solhint-disable-next-line not-rely-on-time
if (deadline < block.timestamp) {
return false;
}
bytes32 typeHash = _typeHash();
if (typeHash == bytes32(0)) {
// Prevent accidental signature validation for functions that don't have an associated type hash.
return false;
}
// All type hashes have this format: (bytes calldata, address sender, uint256 nonce, uint256 deadline).
bytes32 structHash = keccak256(abi.encode(typeHash, keccak256(_calldata()), msg.sender, nonce, deadline));
bytes32 digest = _hashTypedDataV4(structHash);
(uint8 v, bytes32 r, bytes32 s) = _signature();
address recoveredAddress = ecrecover(digest, v, r, s);
// ecrecover returns the zero address on recover failure, so we need to handle that explicitly.
return recoveredAddress != address(0) && recoveredAddress == user;
}
/**
* @dev Returns the EIP712 type hash for the current entry point function, which can be identified by its function
* selector (available as `msg.sig`).
*
* The type hash must conform to the following format:
* <name>(bytes calldata, address sender, uint256 nonce, uint256 deadline)
*
* If 0x00, all signatures will be considered invalid.
*/
function _typeHash() internal view virtual returns (bytes32);
/**
* @dev Extracts the signature deadline from extra calldata.
*
* This function returns bogus data if no signature is included.
*/
function _deadline() internal pure returns (uint256) {
// The deadline is the first extra argument at the end of the original calldata.
return uint256(_decodeExtraCalldataWord(0));
}
/**
* @dev Extracts the signature parameters from extra calldata.
*
* This function returns bogus data if no signature is included. This is not a security risk, as that data would not
* be considered a valid signature in the first place.
*/
function _signature()
internal
pure
returns (
uint8 v,
bytes32 r,
bytes32 s
)
{
// v, r and s are appended after the signature deadline, in that order.
v = uint8(uint256(_decodeExtraCalldataWord(0x20)));
r = _decodeExtraCalldataWord(0x40);
s = _decodeExtraCalldataWord(0x60);
}
/**
* @dev Returns the original calldata, without the extra bytes containing the signature.
*
* This function returns bogus data if no signature is included.
*/
function _calldata() internal pure returns (bytes memory result) {
result = msg.data; // A calldata to memory assignment results in memory allocation and copy of contents.
if (result.length > _EXTRA_CALLDATA_LENGTH) {
// solhint-disable-next-line no-inline-assembly
assembly {
// We simply overwrite the array length with the reduced one.
mstore(result, sub(calldatasize(), _EXTRA_CALLDATA_LENGTH))
}
}
}
/**
* @dev Returns a 256 bit word from 'extra' calldata, at some offset from the expected end of the original calldata.
*
* This function returns bogus data if no signature is included.
*/
function _decodeExtraCalldataWord(uint256 offset) private pure returns (bytes32 result) {
// solhint-disable-next-line no-inline-assembly
assembly {
result := calldataload(add(sub(calldatasize(), _EXTRA_CALLDATA_LENGTH), offset))
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
// Based on the ReentrancyGuard library from OpenZeppelin contracts, altered to reduce bytecode size.
// Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using
// private functions, we achieve the same end result with slightly higher runtime gas costs but reduced bytecode size.
/**
* @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 make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_enterNonReentrant();
_;
_exitNonReentrant();
}
function _enterNonReentrant() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
_require(_status != _ENTERED, Errors.REENTRANCY);
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _exitNonReentrant() private {
// 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: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma experimental ABIEncoderV2;
import "../../lib/openzeppelin/IERC20.sol";
import "./IWETH.sol";
import "./IAsset.sol";
import "./IAuthorizer.sol";
import "./IFlashLoanRecipient.sol";
import "../ProtocolFeesCollector.sol";
import "../../lib/helpers/ISignaturesValidator.sol";
import "../../lib/helpers/ITemporarilyPausable.sol";
pragma solidity ^0.7.0;
/**
* @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that
* don't override one of these declarations.
*/
interface IVault is ISignaturesValidator, ITemporarilyPausable {
// Generalities about the Vault:
//
// - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are
// transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling
// `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by
// calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning
// a boolean value: in these scenarios, a non-reverting call is assumed to be successful.
//
// - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g.
// while execution control is transferred to a token contract during a swap) will result in a revert. View
// functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results.
// Contracts calling view functions in the Vault must make sure the Vault has not already been entered.
//
// - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools.
// Authorizer
//
// Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists
// outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller
// can perform a given action.
/**
* @dev Returns the Vault's Authorizer.
*/
function getAuthorizer() external view returns (IAuthorizer);
/**
* @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this.
*
* Emits an `AuthorizerChanged` event.
*/
function setAuthorizer(IAuthorizer newAuthorizer) external;
/**
* @dev Emitted when a new authorizer is set by `setAuthorizer`.
*/
event AuthorizerChanged(IAuthorizer indexed newAuthorizer);
// Relayers
//
// Additionally, it is possible for an account to perform certain actions on behalf of another one, using their
// Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions,
// and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield
// this power, two things must occur:
// - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This
// means that Balancer governance must approve each individual contract to act as a relayer for the intended
// functions.
// - Each user must approve the relayer to act on their behalf.
// This double protection means users cannot be tricked into approving malicious relayers (because they will not
// have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised
// Authorizer or governance drain user funds, since they would also need to be approved by each individual user.
/**
* @dev Returns true if `user` has approved `relayer` to act as a relayer for them.
*/
function hasApprovedRelayer(address user, address relayer) external view returns (bool);
/**
* @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise.
*
* Emits a `RelayerApprovalChanged` event.
*/
function setRelayerApproval(
address sender,
address relayer,
bool approved
) external;
/**
* @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`.
*/
event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved);
// Internal Balance
//
// Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later
// transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination
// when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced
// gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.
//
// Internal Balance management features batching, which means a single contract call can be used to perform multiple
// operations of different kinds, with different senders and recipients, at once.
/**
* @dev Returns `user`'s Internal Balance for a set of tokens.
*/
function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory);
/**
* @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)
* and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as
* it lets integrators reuse a user's Vault allowance.
*
* For each operation, if the caller is not `sender`, it must be an authorized relayer for them.
*/
function manageUserBalance(UserBalanceOp[] memory ops) external payable;
/**
* @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received
without manual WETH wrapping or unwrapping.
*/
struct UserBalanceOp {
UserBalanceOpKind kind;
IAsset asset;
uint256 amount;
address sender;
address payable recipient;
}
// There are four possible operations in `manageUserBalance`:
//
// - DEPOSIT_INTERNAL
// Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding
// `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`.
//
// ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped
// and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is
// relevant for relayers).
//
// Emits an `InternalBalanceChanged` event.
//
//
// - WITHDRAW_INTERNAL
// Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`.
//
// ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send
// it to the recipient as ETH.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_INTERNAL
// Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_EXTERNAL
// Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by
// relayers, as it lets them reuse a user's Vault allowance.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `ExternalBalanceTransfer` event.
enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL }
/**
* @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through
* interacting with Pools using Internal Balance.
*
* Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH
* address.
*/
event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta);
/**
* @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account.
*/
event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount);
// Pools
//
// There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced
// functionality:
//
// - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the
// balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads),
// which increase with the number of registered tokens.
//
// - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the
// balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted
// constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are
// independent of the number of registered tokens.
//
// - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like
// minimal swap info Pools, these are called via IMinimalSwapInfoPool.
enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN }
/**
* @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which
* is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be
* changed.
*
* The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`,
* depending on the chosen specialization setting. This contract is known as the Pool's contract.
*
* Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words,
* multiple Pools may share the same contract.
*
* Emits a `PoolRegistered` event.
*/
function registerPool(PoolSpecialization specialization) external returns (bytes32);
/**
* @dev Emitted when a Pool is registered by calling `registerPool`.
*/
event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization);
/**
* @dev Returns a Pool's contract address and specialization setting.
*/
function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);
/**
* @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens,
* exit by receiving registered tokens, and can only swap registered tokens.
*
* Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length
* of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in
* ascending order.
*
* The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset
* Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`,
* depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore
* expected to be highly secured smart contracts with sound design principles, and the decision to register an
* Asset Manager should not be made lightly.
*
* Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset
* Manager is set, it cannot be changed except by deregistering the associated token and registering again with a
* different Asset Manager.
*
* Emits a `TokensRegistered` event.
*/
function registerTokens(
bytes32 poolId,
IERC20[] memory tokens,
address[] memory assetManagers
) external;
/**
* @dev Emitted when a Pool registers tokens by calling `registerTokens`.
*/
event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers);
/**
* @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total
* balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens
* must be deregistered in the same `deregisterTokens` call.
*
* A deregistered token can be re-registered later on, possibly with a different Asset Manager.
*
* Emits a `TokensDeregistered` event.
*/
function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external;
/**
* @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`.
*/
event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens);
/**
* @dev Returns detailed information for a Pool's registered token.
*
* `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens
* withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token`
* equals the sum of `cash` and `managed`.
*
* Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`,
* `managed` or `total` balance to be greater than 2^112 - 1.
*
* `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a
* join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for
* example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a
* change for this purpose, and will update `lastChangeBlock`.
*
* `assetManager` is the Pool's token Asset Manager.
*/
function getPoolTokenInfo(bytes32 poolId, IERC20 token)
external
view
returns (
uint256 cash,
uint256 managed,
uint256 lastChangeBlock,
address assetManager
);
/**
* @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of
* the tokens' `balances` changed.
*
* The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all
* Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order.
*
* If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same
* order as passed to `registerTokens`.
*
* Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are
* the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo`
* instead.
*/
function getPoolTokens(bytes32 poolId)
external
view
returns (
IERC20[] memory tokens,
uint256[] memory balances,
uint256 lastChangeBlock
);
/**
* @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will
* trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized
* Pool shares.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount
* to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces
* these maximums.
*
* If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable
* this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the
* WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent
* back to the caller (not the sender, which is important for relayers).
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be
* sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final
* `assets` array might not be sorted. Pools with no registered tokens cannot be joined.
*
* If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only
* be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be
* withdrawn from Internal Balance: attempting to do so will trigger a revert.
*
* This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed
* directly to the Pool's contract, as is `recipient`.
*
* Emits a `PoolBalanceChanged` event.
*/
function joinPool(
bytes32 poolId,
address sender,
address recipient,
JoinPoolRequest memory request
) external payable;
struct JoinPoolRequest {
IAsset[] assets;
uint256[] maxAmountsIn;
bytes userData;
bool fromInternalBalance;
}
/**
* @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will
* trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized
* Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see
* `getPoolTokenInfo`).
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum
* token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault:
* it just enforces these minimums.
*
* If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To
* enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead
* of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit.
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must
* be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the
* final `assets` array might not be sorted. Pools with no registered tokens cannot be exited.
*
* If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise,
* an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to
* do so will trigger a revert.
*
* `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the
* `tokens` array. This array must match the Pool's registered tokens.
*
* This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and
* passed directly to the Pool's contract.
*
* Emits a `PoolBalanceChanged` event.
*/
function exitPool(
bytes32 poolId,
address sender,
address payable recipient,
ExitPoolRequest memory request
) external;
struct ExitPoolRequest {
IAsset[] assets;
uint256[] minAmountsOut;
bytes userData;
bool toInternalBalance;
}
/**
* @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively.
*/
event PoolBalanceChanged(
bytes32 indexed poolId,
address indexed liquidityProvider,
IERC20[] tokens,
int256[] deltas,
uint256[] protocolFeeAmounts
);
enum PoolBalanceChangeKind { JOIN, EXIT }
// Swaps
//
// Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this,
// they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be
// aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote.
//
// The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
// In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
// and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
// More complex swaps, such as one token in to multiple tokens out can be achieved by batching together
// individual swaps.
//
// There are two swap kinds:
// - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the
// `onSwap` hook) the amount of tokens out (to send to the recipient).
// - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines
// (via the `onSwap` hook) the amount of tokens in (to receive from the sender).
//
// Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with
// the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated
// tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended
// swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at
// the final intended token.
//
// In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal
// Balance) after all individual swaps have been completed, and the net token balance change computed. This makes
// certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost
// much less gas than they would otherwise.
//
// It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple
// Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only
// updating the Pool's internal accounting).
//
// To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token
// involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the
// minimum amount of tokens to receive (by passing a negative value) is specified.
//
// Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after
// this point in time (e.g. if the transaction failed to be included in a block promptly).
//
// If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do
// the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be
// passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the
// same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers).
//
// Finally, Internal Balance can be used when either sending or receiving tokens.
enum SwapKind { GIVEN_IN, GIVEN_OUT }
/**
* @dev Performs a swap with a single Pool.
*
* If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens
* taken from the Pool, which must be greater than or equal to `limit`.
*
* If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens
* sent to the Pool, which must be less than or equal to `limit`.
*
* Internal Balance usage and the recipient are determined by the `funds` struct.
*
* Emits a `Swap` event.
*/
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external payable returns (uint256);
/**
* @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
* the `kind` value.
*
* `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
* Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct SingleSwap {
bytes32 poolId;
SwapKind kind;
IAsset assetIn;
IAsset assetOut;
uint256 amount;
bytes userData;
}
/**
* @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either
* the amount of tokens sent to or received from the Pool, depending on the `kind` value.
*
* Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the
* Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at
* the same index in the `assets` array.
*
* Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a
* Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or
* `amountOut` depending on the swap kind.
*
* Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out
* of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal
* the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.
*
* The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,
* or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and
* out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to
* or unwrapped from WETH by the Vault.
*
* Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies
* the minimum or maximum amount of each token the vault is allowed to transfer.
*
* `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the
* equivalent `swap` call.
*
* Emits `Swap` events.
*/
function batchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
int256[] memory limits,
uint256 deadline
) external payable returns (int256[] memory);
/**
* @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the
* `assets` array passed to that function, and ETH assets are converted to WETH.
*
* If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out
* from the previous swap, depending on the swap kind.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct BatchSwapStep {
bytes32 poolId;
uint256 assetInIndex;
uint256 assetOutIndex;
uint256 amount;
bytes userData;
}
/**
* @dev Emitted for each individual swap performed by `swap` or `batchSwap`.
*/
event Swap(
bytes32 indexed poolId,
IERC20 indexed tokenIn,
IERC20 indexed tokenOut,
uint256 amountIn,
uint256 amountOut
);
/**
* @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
* `recipient` account.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
* transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
* must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
* `joinPool`.
*
* If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
* transferred. This matches the behavior of `exitPool`.
*
* Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
* revert.
*/
struct FundManagement {
address sender;
bool fromInternalBalance;
address payable recipient;
bool toInternalBalance;
}
/**
* @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be
* simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result.
*
* Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH)
* the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it
* receives are the same that an equivalent `batchSwap` call would receive.
*
* Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct.
* This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens,
* approve them for the Vault, or even know a user's address.
*
* Note that this function is not 'view' (due to implementation details): the client code must explicitly execute
* eth_call instead of eth_sendTransaction.
*/
function queryBatchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds
) external returns (int256[] memory assetDeltas);
// Flash Loans
/**
* @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it,
* and then reverting unless the tokens plus a proportional protocol fee have been returned.
*
* The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount
* for each token contract. `tokens` must be sorted in ascending order.
*
* The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the
* `receiveFlashLoan` call.
*
* Emits `FlashLoan` events.
*/
function flashLoan(
IFlashLoanRecipient recipient,
IERC20[] memory tokens,
uint256[] memory amounts,
bytes memory userData
) external;
/**
* @dev Emitted for each individual flash loan performed by `flashLoan`.
*/
event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount);
// Asset Management
//
// Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's
// tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see
// `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly
// controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the
// prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore
// not constrained to the tokens they are managing, but extends to the entire Pool's holdings.
//
// However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit,
// for example by lending unused tokens out for interest, or using them to participate in voting protocols.
//
// This concept is unrelated to the IAsset interface.
/**
* @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates.
*
* Pool Balance management features batching, which means a single contract call can be used to perform multiple
* operations of different kinds, with different Pools and tokens, at once.
*
* For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`.
*/
function managePoolBalance(PoolBalanceOp[] memory ops) external;
struct PoolBalanceOp {
PoolBalanceOpKind kind;
bytes32 poolId;
IERC20 token;
uint256 amount;
}
/**
* Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged.
*
* Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged.
*
* Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total.
* The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss).
*/
enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE }
/**
* @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`.
*/
event PoolBalanceManaged(
bytes32 indexed poolId,
address indexed assetManager,
IERC20 indexed token,
int256 cashDelta,
int256 managedDelta
);
// Protocol Fees
//
// Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by
// permissioned accounts.
//
// There are two kinds of protocol fees:
//
// - flash loan fees: charged on all flash loans, as a percentage of the amounts lent.
//
// - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including
// swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather,
// Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the
// Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as
// exiting a Pool in debt without first paying their share.
/**
* @dev Returns the current protocol fee module.
*/
function getProtocolFeesCollector() external view returns (ProtocolFeesCollector);
/**
* @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an
* error in some part of the system.
*
* The Vault can only be paused during an initial time period, after which pausing is forever disabled.
*
* While the contract is paused, the following features are disabled:
* - depositing and transferring internal balance
* - transferring external balance (using the Vault's allowance)
* - swaps
* - joining Pools
* - Asset Manager interactions
*
* Internal Balance can still be withdrawn, and Pools exited.
*/
function setPaused(bool paused) external;
/**
* @dev Returns the Vault's WETH instance.
*/
function WETH() external view returns (IWETH);
// solhint-disable-previous-line func-name-mixedcase
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
interface IAuthentication {
/**
* @dev Returns the action identifier associated with the external function described by `selector`.
*/
function getActionId(bytes4 selector) external view returns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev Interface for the TemporarilyPausable helper.
*/
interface ITemporarilyPausable {
/**
* @dev Emitted every time the pause state changes by `_setPaused`.
*/
event PausedStateChanged(bool paused);
/**
* @dev Returns the current paused state.
*/
function getPausedState()
external
view
returns (
bool paused,
uint256 pauseWindowEndTime,
uint256 bufferPeriodEndTime
);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev Interface for the SignatureValidator helper, used to support meta-transactions.
*/
interface ISignaturesValidator {
/**
* @dev Returns the EIP712 domain separator.
*/
function getDomainSeparator() external view returns (bytes32);
/**
* @dev Returns the next nonce used by an address to sign messages.
*/
function getNextNonce(address user) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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 */
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) {
_HASHED_NAME = keccak256(bytes(name));
_HASHED_VERSION = keccak256(bytes(version));
_TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view virtual returns (bytes32) {
return keccak256(abi.encode(_TYPE_HASH, _HASHED_NAME, _HASHED_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) {
// Silence state mutability warning without generating bytecode.
// See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and
// https://github.com/ethereum/solidity/issues/2691
this;
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero
* address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like
* types.
*
* This concept is unrelated to a Pool's Asset Managers.
*/
interface IAsset {
// solhint-disable-previous-line no-empty-blocks
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
// Inspired by Aave Protocol's IFlashLoanReceiver.
import "../../lib/openzeppelin/IERC20.sol";
interface IFlashLoanRecipient {
/**
* @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient.
*
* At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this
* call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the
* Vault, or else the entire flash loan will revert.
*
* `userData` is the same value passed in the `IVault.flashLoan` call.
*/
function receiveFlashLoan(
IERC20[] memory tokens,
uint256[] memory amounts,
uint256[] memory feeAmounts,
bytes memory userData
) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/openzeppelin/IERC20.sol";
import "../lib/helpers/InputHelpers.sol";
import "../lib/helpers/Authentication.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./interfaces/IVault.sol";
import "./interfaces/IAuthorizer.sol";
/**
* @dev This an auxiliary contract to the Vault, deployed by it during construction. It offloads some of the tasks the
* Vault performs to reduce its overall bytecode size.
*
* The current values for all protocol fee percentages are stored here, and any tokens charged as protocol fees are
* sent to this contract, where they may be withdrawn by authorized entities. All authorization tasks are delegated
* to the Vault's own authorizer.
*/
contract ProtocolFeesCollector is Authentication, ReentrancyGuard {
using SafeERC20 for IERC20;
// Absolute maximum fee percentages (1e18 = 100%, 1e16 = 1%).
uint256 private constant _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE = 50e16; // 50%
uint256 private constant _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE = 1e16; // 1%
IVault public immutable vault;
// All fee percentages are 18-decimal fixed point numbers.
// The swap fee is charged whenever a swap occurs, as a percentage of the fee charged by the Pool. These are not
// actually charged on each individual swap: the `Vault` relies on the Pools being honest and reporting fees due
// when users join and exit them.
uint256 private _swapFeePercentage;
// The flash loan fee is charged whenever a flash loan occurs, as a percentage of the tokens lent.
uint256 private _flashLoanFeePercentage;
event SwapFeePercentageChanged(uint256 newSwapFeePercentage);
event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage);
constructor(IVault _vault)
// The ProtocolFeesCollector is a singleton, so it simply uses its own address to disambiguate action
// identifiers.
Authentication(bytes32(uint256(address(this))))
{
vault = _vault;
}
function withdrawCollectedFees(
IERC20[] calldata tokens,
uint256[] calldata amounts,
address recipient
) external nonReentrant authenticate {
InputHelpers.ensureInputLengthMatch(tokens.length, amounts.length);
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
uint256 amount = amounts[i];
token.safeTransfer(recipient, amount);
}
}
function setSwapFeePercentage(uint256 newSwapFeePercentage) external authenticate {
_require(newSwapFeePercentage <= _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE, Errors.SWAP_FEE_PERCENTAGE_TOO_HIGH);
_swapFeePercentage = newSwapFeePercentage;
emit SwapFeePercentageChanged(newSwapFeePercentage);
}
function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external authenticate {
_require(
newFlashLoanFeePercentage <= _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE,
Errors.FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH
);
_flashLoanFeePercentage = newFlashLoanFeePercentage;
emit FlashLoanFeePercentageChanged(newFlashLoanFeePercentage);
}
function getSwapFeePercentage() external view returns (uint256) {
return _swapFeePercentage;
}
function getFlashLoanFeePercentage() external view returns (uint256) {
return _flashLoanFeePercentage;
}
function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts) {
feeAmounts = new uint256[](tokens.length);
for (uint256 i = 0; i < tokens.length; ++i) {
feeAmounts[i] = tokens[i].balanceOf(address(this));
}
}
function getAuthorizer() external view returns (IAuthorizer) {
return _getAuthorizer();
}
function _canPerform(bytes32 actionId, address account) internal view override returns (bool) {
return _getAuthorizer().canPerform(actionId, account, address(this));
}
function _getAuthorizer() internal view returns (IAuthorizer) {
return vault.getAuthorizer();
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../openzeppelin/IERC20.sol";
import "./BalancerErrors.sol";
import "../../vault/interfaces/IAsset.sol";
library InputHelpers {
function ensureInputLengthMatch(uint256 a, uint256 b) internal pure {
_require(a == b, Errors.INPUT_LENGTH_MISMATCH);
}
function ensureInputLengthMatch(
uint256 a,
uint256 b,
uint256 c
) internal pure {
_require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH);
}
function ensureArrayIsSorted(IAsset[] memory array) internal pure {
address[] memory addressArray;
// solhint-disable-next-line no-inline-assembly
assembly {
addressArray := array
}
ensureArrayIsSorted(addressArray);
}
function ensureArrayIsSorted(IERC20[] memory array) internal pure {
address[] memory addressArray;
// solhint-disable-next-line no-inline-assembly
assembly {
addressArray := array
}
ensureArrayIsSorted(addressArray);
}
function ensureArrayIsSorted(address[] memory array) internal pure {
if (array.length < 2) {
return;
}
address previous = array[0];
for (uint256 i = 1; i < array.length; ++i) {
address current = array[i];
_require(previous < current, Errors.UNSORTED_ARRAY);
previous = current;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
import "./IERC20.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 {
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(address(token), abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(address(token), abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @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).
*
* WARNING: `token` is assumed to be a contract: calls to EOAs will *not* revert.
*/
function _callOptionalReturn(address 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.
(bool success, bytes memory returndata) = token.call(data);
// If the low-level call didn't succeed we return whatever was returned from it.
assembly {
if eq(success, 0) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
// Finally we check the returndata size is either zero or true - note that this check will always pass for EOAs
_require(returndata.length == 0 || abi.decode(returndata, (bool)), Errors.SAFE_ERC20_CALL_FAILED);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/math/FixedPoint.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./ProtocolFeesCollector.sol";
import "./VaultAuthorization.sol";
import "./interfaces/IVault.sol";
/**
* @dev To reduce the bytecode size of the Vault, most of the protocol fee logic is not here, but in the
* ProtocolFeesCollector contract.
*/
abstract contract Fees is IVault {
using SafeERC20 for IERC20;
ProtocolFeesCollector private immutable _protocolFeesCollector;
constructor() {
_protocolFeesCollector = new ProtocolFeesCollector(IVault(this));
}
function getProtocolFeesCollector() public view override returns (ProtocolFeesCollector) {
return _protocolFeesCollector;
}
/**
* @dev Returns the protocol swap fee percentage.
*/
function _getProtocolSwapFeePercentage() internal view returns (uint256) {
return getProtocolFeesCollector().getSwapFeePercentage();
}
/**
* @dev Returns the protocol fee amount to charge for a flash loan of `amount`.
*/
function _calculateFlashLoanFeeAmount(uint256 amount) internal view returns (uint256) {
// Fixed point multiplication introduces error: we round up, which means in certain scenarios the charged
// percentage can be slightly higher than intended.
uint256 percentage = getProtocolFeesCollector().getFlashLoanFeePercentage();
return FixedPoint.mulUp(amount, percentage);
}
function _payFeeAmount(IERC20 token, uint256 amount) internal {
if (amount > 0) {
token.safeTransfer(address(getProtocolFeesCollector()), amount);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./LogExpMath.sol";
import "../helpers/BalancerErrors.sol";
/* solhint-disable private-vars-leading-underscore */
library FixedPoint {
uint256 internal constant ONE = 1e18; // 18 decimal places
uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14)
// Minimum base for the power function when the exponent is 'free' (larger than ONE).
uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18;
function add(uint256 a, uint256 b) internal pure returns (uint256) {
// Fixed Point addition is the same as regular checked addition
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
// Fixed Point addition is the same as regular checked addition
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
function mulDown(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
_require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);
return product / ONE;
}
function mulUp(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
_require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);
if (product == 0) {
return 0;
} else {
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return ((product - 1) / ONE) + 1;
}
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
uint256 aInflated = a * ONE;
_require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
return aInflated / b;
}
}
function divUp(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
uint256 aInflated = a * ONE;
_require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return ((aInflated - 1) / b) + 1;
}
}
/**
* @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above
* the true value (that is, the error function expected - actual is always positive).
*/
function powDown(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 raw = LogExpMath.pow(x, y);
uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);
if (raw < maxError) {
return 0;
} else {
return sub(raw, maxError);
}
}
/**
* @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below
* the true value (that is, the error function expected - actual is always negative).
*/
function powUp(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 raw = LogExpMath.pow(x, y);
uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);
return add(raw, maxError);
}
/**
* @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1.
*
* Useful when computing the complement for values with some level of relative error, as it strips this error and
* prevents intermediate negative values.
*/
function complement(uint256 x) internal pure returns (uint256) {
return (x < ONE) ? (ONE - x) : 0;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General internal License for more details.
// You should have received a copy of the GNU General internal License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/* solhint-disable */
/**
* @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument).
*
* Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural
* exponentiation and logarithm (where the base is Euler's number).
*
* @author Fernando Martinelli - @fernandomartinelli
* @author Sergio Yuhjtman - @sergioyuhjtman
* @author Daniel Fernandez - @dmf7z
*/
library LogExpMath {
// All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying
// two numbers, and multiply by ONE when dividing them.
// All arguments and return values are 18 decimal fixed point numbers.
int256 constant ONE_18 = 1e18;
// Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the
// case of ln36, 36 decimals.
int256 constant ONE_20 = 1e20;
int256 constant ONE_36 = 1e36;
// The domain of natural exponentiation is bound by the word size and number of decimals used.
//
// Because internally the result will be stored using 20 decimals, the largest possible result is
// (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221.
// The smallest possible result is 10^(-18), which makes largest negative argument
// ln(10^(-18)) = -41.446531673892822312.
// We use 130.0 and -41.0 to have some safety margin.
int256 constant MAX_NATURAL_EXPONENT = 130e18;
int256 constant MIN_NATURAL_EXPONENT = -41e18;
// Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point
// 256 bit integer.
int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17;
int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17;
uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20);
// 18 decimal constants
int256 constant x0 = 128000000000000000000; // 2ˆ7
int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals)
int256 constant x1 = 64000000000000000000; // 2ˆ6
int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals)
// 20 decimal constants
int256 constant x2 = 3200000000000000000000; // 2ˆ5
int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2)
int256 constant x3 = 1600000000000000000000; // 2ˆ4
int256 constant a3 = 888611052050787263676000000; // eˆ(x3)
int256 constant x4 = 800000000000000000000; // 2ˆ3
int256 constant a4 = 298095798704172827474000; // eˆ(x4)
int256 constant x5 = 400000000000000000000; // 2ˆ2
int256 constant a5 = 5459815003314423907810; // eˆ(x5)
int256 constant x6 = 200000000000000000000; // 2ˆ1
int256 constant a6 = 738905609893065022723; // eˆ(x6)
int256 constant x7 = 100000000000000000000; // 2ˆ0
int256 constant a7 = 271828182845904523536; // eˆ(x7)
int256 constant x8 = 50000000000000000000; // 2ˆ-1
int256 constant a8 = 164872127070012814685; // eˆ(x8)
int256 constant x9 = 25000000000000000000; // 2ˆ-2
int256 constant a9 = 128402541668774148407; // eˆ(x9)
int256 constant x10 = 12500000000000000000; // 2ˆ-3
int256 constant a10 = 113314845306682631683; // eˆ(x10)
int256 constant x11 = 6250000000000000000; // 2ˆ-4
int256 constant a11 = 106449445891785942956; // eˆ(x11)
/**
* @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent.
*
* Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`.
*/
function pow(uint256 x, uint256 y) internal pure returns (uint256) {
if (y == 0) {
// We solve the 0^0 indetermination by making it equal one.
return uint256(ONE_18);
}
if (x == 0) {
return 0;
}
// Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to
// arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means
// x^y = exp(y * ln(x)).
// The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range.
_require(x < 2**255, Errors.X_OUT_OF_BOUNDS);
int256 x_int256 = int256(x);
// We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In
// both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end.
// This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range.
_require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS);
int256 y_int256 = int256(y);
int256 logx_times_y;
if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) {
int256 ln_36_x = ln_36(x_int256);
// ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just
// bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal
// multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the
// (downscaled) last 18 decimals.
logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18);
} else {
logx_times_y = ln(x_int256) * y_int256;
}
logx_times_y /= ONE_18;
// Finally, we compute exp(y * ln(x)) to arrive at x^y
_require(
MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT,
Errors.PRODUCT_OUT_OF_BOUNDS
);
return uint256(exp(logx_times_y));
}
/**
* @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent.
*
* Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`.
*/
function exp(int256 x) internal pure returns (int256) {
_require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT);
if (x < 0) {
// We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it
// fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT).
// Fixed point division requires multiplying by ONE_18.
return ((ONE_18 * ONE_18) / exp(-x));
}
// First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n,
// where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7
// because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the
// decomposition.
// At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this
// decomposition, which will be lower than the smallest x_n.
// exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1.
// We mutate x by subtracting x_n, making it the remainder of the decomposition.
// The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause
// intermediate overflows. Instead we store them as plain integers, with 0 decimals.
// Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the
// decomposition.
// For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct
// it and compute the accumulated product.
int256 firstAN;
if (x >= x0) {
x -= x0;
firstAN = a0;
} else if (x >= x1) {
x -= x1;
firstAN = a1;
} else {
firstAN = 1; // One with no decimal places
}
// We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the
// smaller terms.
x *= 100;
// `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point
// one. Recall that fixed point multiplication requires dividing by ONE_20.
int256 product = ONE_20;
if (x >= x2) {
x -= x2;
product = (product * a2) / ONE_20;
}
if (x >= x3) {
x -= x3;
product = (product * a3) / ONE_20;
}
if (x >= x4) {
x -= x4;
product = (product * a4) / ONE_20;
}
if (x >= x5) {
x -= x5;
product = (product * a5) / ONE_20;
}
if (x >= x6) {
x -= x6;
product = (product * a6) / ONE_20;
}
if (x >= x7) {
x -= x7;
product = (product * a7) / ONE_20;
}
if (x >= x8) {
x -= x8;
product = (product * a8) / ONE_20;
}
if (x >= x9) {
x -= x9;
product = (product * a9) / ONE_20;
}
// x10 and x11 are unnecessary here since we have high enough precision already.
// Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series
// expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!).
int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places.
int256 term; // Each term in the sum, where the nth term is (x^n / n!).
// The first term is simply x.
term = x;
seriesSum += term;
// Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number,
// multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not.
term = ((term * x) / ONE_20) / 2;
seriesSum += term;
term = ((term * x) / ONE_20) / 3;
seriesSum += term;
term = ((term * x) / ONE_20) / 4;
seriesSum += term;
term = ((term * x) / ONE_20) / 5;
seriesSum += term;
term = ((term * x) / ONE_20) / 6;
seriesSum += term;
term = ((term * x) / ONE_20) / 7;
seriesSum += term;
term = ((term * x) / ONE_20) / 8;
seriesSum += term;
term = ((term * x) / ONE_20) / 9;
seriesSum += term;
term = ((term * x) / ONE_20) / 10;
seriesSum += term;
term = ((term * x) / ONE_20) / 11;
seriesSum += term;
term = ((term * x) / ONE_20) / 12;
seriesSum += term;
// 12 Taylor terms are sufficient for 18 decimal precision.
// We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor
// approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply
// all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication),
// and then drop two digits to return an 18 decimal value.
return (((product * seriesSum) / ONE_20) * firstAN) / 100;
}
/**
* @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function ln(int256 a) internal pure returns (int256) {
// The real natural logarithm is not defined for negative numbers or zero.
_require(a > 0, Errors.OUT_OF_BOUNDS);
if (a < ONE_18) {
// Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less
// than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call.
// Fixed point division requires multiplying by ONE_18.
return (-ln((ONE_18 * ONE_18) / a));
}
// First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which
// we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is,
// ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot
// be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a.
// At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this
// decomposition, which will be lower than the smallest a_n.
// ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1.
// We mutate a by subtracting a_n, making it the remainder of the decomposition.
// For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point
// numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by
// ONE_18 to convert them to fixed point.
// For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide
// by it and compute the accumulated sum.
int256 sum = 0;
if (a >= a0 * ONE_18) {
a /= a0; // Integer, not fixed point division
sum += x0;
}
if (a >= a1 * ONE_18) {
a /= a1; // Integer, not fixed point division
sum += x1;
}
// All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format.
sum *= 100;
a *= 100;
// Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them.
if (a >= a2) {
a = (a * ONE_20) / a2;
sum += x2;
}
if (a >= a3) {
a = (a * ONE_20) / a3;
sum += x3;
}
if (a >= a4) {
a = (a * ONE_20) / a4;
sum += x4;
}
if (a >= a5) {
a = (a * ONE_20) / a5;
sum += x5;
}
if (a >= a6) {
a = (a * ONE_20) / a6;
sum += x6;
}
if (a >= a7) {
a = (a * ONE_20) / a7;
sum += x7;
}
if (a >= a8) {
a = (a * ONE_20) / a8;
sum += x8;
}
if (a >= a9) {
a = (a * ONE_20) / a9;
sum += x9;
}
if (a >= a10) {
a = (a * ONE_20) / a10;
sum += x10;
}
if (a >= a11) {
a = (a * ONE_20) / a11;
sum += x11;
}
// a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series
// that converges rapidly for values of `a` close to one - the same one used in ln_36.
// Let z = (a - 1) / (a + 1).
// ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires
// division by ONE_20.
int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);
int256 z_squared = (z * z) / ONE_20;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_20;
seriesSum += num / 3;
num = (num * z_squared) / ONE_20;
seriesSum += num / 5;
num = (num * z_squared) / ONE_20;
seriesSum += num / 7;
num = (num * z_squared) / ONE_20;
seriesSum += num / 9;
num = (num * z_squared) / ONE_20;
seriesSum += num / 11;
// 6 Taylor terms are sufficient for 36 decimal precision.
// Finally, we multiply by 2 (non fixed point) to compute ln(remainder)
seriesSum *= 2;
// We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both
// with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal
// value.
return (sum + seriesSum) / 100;
}
/**
* @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument argument.
*/
function log(int256 arg, int256 base) internal pure returns (int256) {
// This performs a simple base change: log(arg, base) = ln(arg) / ln(base).
// Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by
// upscaling.
int256 logBase;
if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) {
logBase = ln_36(base);
} else {
logBase = ln(base) * ONE_18;
}
int256 logArg;
if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) {
logArg = ln_36(arg);
} else {
logArg = ln(arg) * ONE_18;
}
// When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places
return (logArg * ONE_18) / logBase;
}
/**
* @dev High precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument,
* for x close to one.
*
* Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND.
*/
function ln_36(int256 x) private pure returns (int256) {
// Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
// worthwhile.
// First, we transform x to a 36 digit fixed point value.
x *= ONE_18;
// We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
// ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
// division by ONE_36.
int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
int256 z_squared = (z * z) / ONE_36;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_36;
seriesSum += num / 3;
num = (num * z_squared) / ONE_36;
seriesSum += num / 5;
num = (num * z_squared) / ONE_36;
seriesSum += num / 7;
num = (num * z_squared) / ONE_36;
seriesSum += num / 9;
num = (num * z_squared) / ONE_36;
seriesSum += num / 11;
num = (num * z_squared) / ONE_36;
seriesSum += num / 13;
num = (num * z_squared) / ONE_36;
seriesSum += num / 15;
// 8 Taylor terms are sufficient for 36 decimal precision.
// All that remains is multiplying by 2 (non fixed point).
return seriesSum * 2;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow checks.
* Adapted from OpenZeppelin's SafeMath library
*/
library Math {
/**
* @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting 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), Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting 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), Errors.SUB_OVERFLOW);
return c;
}
/**
* @dev Returns the largest of two numbers of 256 bits.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers of 256 bits.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
_require(a == 0 || c / a == b, Errors.MUL_OVERFLOW);
return c;
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
return a / b;
}
function divUp(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
return 1 + (a - 1) / b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
// Based on the EnumerableMap library from OpenZeppelin contracts, altered to include the following:
// * a map from IERC20 to bytes32
// * entries are stored in mappings instead of arrays, reducing implicit storage reads for out-of-bounds checks
// * unchecked_at and unchecked_valueAt, which allow for more gas efficient data reads in some scenarios
// * unchecked_indexOf and unchecked_setAt, which allow for more gas efficient data writes in some scenarios
//
// Additionally, the base private functions that work on bytes32 were removed and replaced with a native implementation
// for IERC20 keys, to reduce bytecode size and runtime costs.
// We're using non-standard casing for the unchecked functions to differentiate them, so we need to turn off that rule
// solhint-disable func-name-mixedcase
import "./IERC20.sol";
import "../helpers/BalancerErrors.sol";
/**
* @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;
* }
* ```
*/
library EnumerableMap {
// The original OpenZeppelin implementation uses a generic Map type with bytes32 keys: this was replaced with
// IERC20ToBytes32Map, which uses IERC20 keys natively, resulting in more dense bytecode.
struct IERC20ToBytes32MapEntry {
IERC20 _key;
bytes32 _value;
}
struct IERC20ToBytes32Map {
// Number of entries in the map
uint256 _length;
// Storage of map keys and values
mapping(uint256 => IERC20ToBytes32MapEntry) _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(IERC20 => 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(
IERC20ToBytes32Map storage map,
IERC20 key,
bytes32 value
) internal returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
// Equivalent to !contains(map, key)
if (keyIndex == 0) {
uint256 previousLength = map._length;
map._entries[previousLength] = IERC20ToBytes32MapEntry({ _key: key, _value: value });
map._length = previousLength + 1;
// The entry is stored at previousLength, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = previousLength + 1;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Updates the value for an entry, given its key's index. The key index can be retrieved via
* {unchecked_indexOf}, and it should be noted that key indices may change when calling {set} or {remove}. O(1).
*
* This function performs one less storage read than {set}, but it should only be used when `index` is known to be
* within bounds.
*/
function unchecked_setAt(
IERC20ToBytes32Map storage map,
uint256 index,
bytes32 value
) internal {
map._entries[index]._value = value;
}
/**
* @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(IERC20ToBytes32Map storage map, IERC20 key) internal returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
// Equivalent to contains(map, key)
if (keyIndex != 0) {
// To delete a key-value pair from the _entries pseudo-array in O(1), we swap the entry to delete with the
// one at the highest index, and then remove this last entry (sometimes called as 'swap and pop').
// This modifies the order of the pseudo-array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._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.
IERC20ToBytes32MapEntry 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
delete map._entries[lastIndex];
map._length = lastIndex;
// 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(IERC20ToBytes32Map storage map, IERC20 key) internal view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function length(IERC20ToBytes32Map storage map) internal view returns (uint256) {
return map._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(IERC20ToBytes32Map storage map, uint256 index) internal view returns (IERC20, bytes32) {
_require(map._length > index, Errors.OUT_OF_BOUNDS);
return unchecked_at(map, index);
}
/**
* @dev Same as {at}, except this doesn't revert if `index` it outside of the map (i.e. if it is equal or larger
* than {length}). O(1).
*
* This function performs one less storage read than {at}, but should only be used when `index` is known to be
* within bounds.
*/
function unchecked_at(IERC20ToBytes32Map storage map, uint256 index) internal view returns (IERC20, bytes32) {
IERC20ToBytes32MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Same as {unchecked_At}, except it only returns the value and not the key (performing one less storage
* read). O(1).
*/
function unchecked_valueAt(IERC20ToBytes32Map storage map, uint256 index) internal view returns (bytes32) {
return map._entries[index]._value;
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map. Reverts with `errorCode` otherwise.
*/
function get(
IERC20ToBytes32Map storage map,
IERC20 key,
uint256 errorCode
) internal view returns (bytes32) {
uint256 index = map._indexes[key];
_require(index > 0, errorCode);
return unchecked_valueAt(map, index - 1);
}
/**
* @dev Returns the index for `key` **plus one**. Does not revert if the key is not in the map, and returns 0
* instead.
*/
function unchecked_indexOf(IERC20ToBytes32Map storage map, IERC20 key) internal view returns (uint256) {
return map._indexes[key];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
// Based on the EnumerableSet library from OpenZeppelin contracts, altered to remove the base private functions that
// work on bytes32, replacing them with a native implementation for address values, to reduce bytecode size and runtime
// costs.
// The `unchecked_at` function was also added, which allows for more gas efficient data reads in some scenarios.
/**
* @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 {
// The original OpenZeppelin implementation uses a generic Set type with bytes32 values: this was replaced with
// AddressSet, which uses address keys natively, resulting in more dense bytecode.
struct AddressSet {
// Storage of set values
address[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(address => 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(AddressSet storage set, address value) internal 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(AddressSet storage set, address value) internal 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.
address 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(AddressSet storage set, address value) internal view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(AddressSet storage set) internal 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(AddressSet storage set, uint256 index) internal view returns (address) {
_require(set._values.length > index, Errors.OUT_OF_BOUNDS);
return unchecked_at(set, index);
}
/**
* @dev Same as {at}, except this doesn't revert if `index` it outside of the set (i.e. if it is equal or larger
* than {length}). O(1).
*
* This function performs one less storage read than {at}, but should only be used when `index` is known to be
* within bounds.
*/
function unchecked_at(AddressSet storage set, uint256 index) internal view returns (address) {
return set._values[index];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @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 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, Errors.SAFE_CAST_VALUE_CANT_FIT_INT256);
return int256(value);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/math/Math.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/helpers/InputHelpers.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./Fees.sol";
import "./PoolTokens.sol";
import "./UserBalance.sol";
import "./interfaces/IBasePool.sol";
/**
* @dev Stores the Asset Managers (by Pool and token), and implements the top level Asset Manager and Pool interfaces,
* such as registering and deregistering tokens, joining and exiting Pools, and informational functions like `getPool`
* and `getPoolTokens`, delegating to specialization-specific functions as needed.
*
* `managePoolBalance` handles all Asset Manager interactions.
*/
abstract contract PoolBalances is Fees, ReentrancyGuard, PoolTokens, UserBalance {
using Math for uint256;
using SafeERC20 for IERC20;
using BalanceAllocation for bytes32;
using BalanceAllocation for bytes32[];
function joinPool(
bytes32 poolId,
address sender,
address recipient,
JoinPoolRequest memory request
) external payable override whenNotPaused {
// This function doesn't have the nonReentrant modifier: it is applied to `_joinOrExit` instead.
// Note that `recipient` is not actually payable in the context of a join - we cast it because we handle both
// joins and exits at once.
_joinOrExit(PoolBalanceChangeKind.JOIN, poolId, sender, payable(recipient), _toPoolBalanceChange(request));
}
function exitPool(
bytes32 poolId,
address sender,
address payable recipient,
ExitPoolRequest memory request
) external override {
// This function doesn't have the nonReentrant modifier: it is applied to `_joinOrExit` instead.
_joinOrExit(PoolBalanceChangeKind.EXIT, poolId, sender, recipient, _toPoolBalanceChange(request));
}
// This has the exact same layout as JoinPoolRequest and ExitPoolRequest, except the `maxAmountsIn` and
// `minAmountsOut` are called `limits`. Internally we use this struct for both since these two functions are quite
// similar, but expose the others to callers for clarity.
struct PoolBalanceChange {
IAsset[] assets;
uint256[] limits;
bytes userData;
bool useInternalBalance;
}
/**
* @dev Converts a JoinPoolRequest into a PoolBalanceChange, with no runtime cost.
*/
function _toPoolBalanceChange(JoinPoolRequest memory request)
private
pure
returns (PoolBalanceChange memory change)
{
// solhint-disable-next-line no-inline-assembly
assembly {
change := request
}
}
/**
* @dev Converts an ExitPoolRequest into a PoolBalanceChange, with no runtime cost.
*/
function _toPoolBalanceChange(ExitPoolRequest memory request)
private
pure
returns (PoolBalanceChange memory change)
{
// solhint-disable-next-line no-inline-assembly
assembly {
change := request
}
}
/**
* @dev Implements both `joinPool` and `exitPool`, based on `kind`.
*/
function _joinOrExit(
PoolBalanceChangeKind kind,
bytes32 poolId,
address sender,
address payable recipient,
PoolBalanceChange memory change
) private nonReentrant withRegisteredPool(poolId) authenticateFor(sender) {
// This function uses a large number of stack variables (poolId, sender and recipient, balances, amounts, fees,
// etc.), which leads to 'stack too deep' issues. It relies on private functions with seemingly arbitrary
// interfaces to work around this limitation.
InputHelpers.ensureInputLengthMatch(change.assets.length, change.limits.length);
// We first check that the caller passed the Pool's registered tokens in the correct order, and retrieve the
// current balance for each.
IERC20[] memory tokens = _translateToIERC20(change.assets);
bytes32[] memory balances = _validateTokensAndGetBalances(poolId, tokens);
// The bulk of the work is done here: the corresponding Pool hook is called, its final balances are computed,
// assets are transferred, and fees are paid.
(
bytes32[] memory finalBalances,
uint256[] memory amountsInOrOut,
uint256[] memory paidProtocolSwapFeeAmounts
) = _callPoolBalanceChange(kind, poolId, sender, recipient, change, balances);
// All that remains is storing the new Pool balances.
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
_setTwoTokenPoolCashBalances(poolId, tokens[0], finalBalances[0], tokens[1], finalBalances[1]);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
_setMinimalSwapInfoPoolBalances(poolId, tokens, finalBalances);
} else {
// PoolSpecialization.GENERAL
_setGeneralPoolBalances(poolId, finalBalances);
}
bool positive = kind == PoolBalanceChangeKind.JOIN; // Amounts in are positive, out are negative
emit PoolBalanceChanged(
poolId,
sender,
tokens,
// We can unsafely cast to int256 because balances are actually stored as uint112
_unsafeCastToInt256(amountsInOrOut, positive),
paidProtocolSwapFeeAmounts
);
}
/**
* @dev Calls the corresponding Pool hook to get the amounts in/out plus protocol fee amounts, and performs the
* associated token transfers and fee payments, returning the Pool's final balances.
*/
function _callPoolBalanceChange(
PoolBalanceChangeKind kind,
bytes32 poolId,
address sender,
address payable recipient,
PoolBalanceChange memory change,
bytes32[] memory balances
)
private
returns (
bytes32[] memory finalBalances,
uint256[] memory amountsInOrOut,
uint256[] memory dueProtocolFeeAmounts
)
{
(uint256[] memory totalBalances, uint256 lastChangeBlock) = balances.totalsAndLastChangeBlock();
IBasePool pool = IBasePool(_getPoolAddress(poolId));
(amountsInOrOut, dueProtocolFeeAmounts) = kind == PoolBalanceChangeKind.JOIN
? pool.onJoinPool(
poolId,
sender,
recipient,
totalBalances,
lastChangeBlock,
_getProtocolSwapFeePercentage(),
change.userData
)
: pool.onExitPool(
poolId,
sender,
recipient,
totalBalances,
lastChangeBlock,
_getProtocolSwapFeePercentage(),
change.userData
);
InputHelpers.ensureInputLengthMatch(balances.length, amountsInOrOut.length, dueProtocolFeeAmounts.length);
// The Vault ignores the `recipient` in joins and the `sender` in exits: it is up to the Pool to keep track of
// their participation.
finalBalances = kind == PoolBalanceChangeKind.JOIN
? _processJoinPoolTransfers(sender, change, balances, amountsInOrOut, dueProtocolFeeAmounts)
: _processExitPoolTransfers(recipient, change, balances, amountsInOrOut, dueProtocolFeeAmounts);
}
/**
* @dev Transfers `amountsIn` from `sender`, checking that they are within their accepted limits, and pays
* accumulated protocol swap fees.
*
* Returns the Pool's final balances, which are the current balances plus `amountsIn` minus accumulated protocol
* swap fees.
*/
function _processJoinPoolTransfers(
address sender,
PoolBalanceChange memory change,
bytes32[] memory balances,
uint256[] memory amountsIn,
uint256[] memory dueProtocolFeeAmounts
) private returns (bytes32[] memory finalBalances) {
// We need to track how much of the received ETH was used and wrapped into WETH to return any excess.
uint256 wrappedEth = 0;
finalBalances = new bytes32[](balances.length);
for (uint256 i = 0; i < change.assets.length; ++i) {
uint256 amountIn = amountsIn[i];
_require(amountIn <= change.limits[i], Errors.JOIN_ABOVE_MAX);
// Receive assets from the sender - possibly from Internal Balance.
IAsset asset = change.assets[i];
_receiveAsset(asset, amountIn, sender, change.useInternalBalance);
if (_isETH(asset)) {
wrappedEth = wrappedEth.add(amountIn);
}
uint256 feeAmount = dueProtocolFeeAmounts[i];
_payFeeAmount(_translateToIERC20(asset), feeAmount);
// Compute the new Pool balances. Note that the fee amount might be larger than `amountIn`,
// resulting in an overall decrease of the Pool's balance for a token.
finalBalances[i] = (amountIn >= feeAmount) // This lets us skip checked arithmetic
? balances[i].increaseCash(amountIn - feeAmount)
: balances[i].decreaseCash(feeAmount - amountIn);
}
// Handle any used and remaining ETH.
_handleRemainingEth(wrappedEth);
}
/**
* @dev Transfers `amountsOut` to `recipient`, checking that they are within their accepted limits, and pays
* accumulated protocol swap fees from the Pool.
*
* Returns the Pool's final balances, which are the current `balances` minus `amountsOut` and fees paid
* (`dueProtocolFeeAmounts`).
*/
function _processExitPoolTransfers(
address payable recipient,
PoolBalanceChange memory change,
bytes32[] memory balances,
uint256[] memory amountsOut,
uint256[] memory dueProtocolFeeAmounts
) private returns (bytes32[] memory finalBalances) {
finalBalances = new bytes32[](balances.length);
for (uint256 i = 0; i < change.assets.length; ++i) {
uint256 amountOut = amountsOut[i];
_require(amountOut >= change.limits[i], Errors.EXIT_BELOW_MIN);
// Send tokens to the recipient - possibly to Internal Balance
IAsset asset = change.assets[i];
_sendAsset(asset, amountOut, recipient, change.useInternalBalance);
uint256 feeAmount = dueProtocolFeeAmounts[i];
_payFeeAmount(_translateToIERC20(asset), feeAmount);
// Compute the new Pool balances. A Pool's token balance always decreases after an exit (potentially by 0).
finalBalances[i] = balances[i].decreaseCash(amountOut.add(feeAmount));
}
}
/**
* @dev Returns the total balance for `poolId`'s `expectedTokens`.
*
* `expectedTokens` must exactly equal the token array returned by `getPoolTokens`: both arrays must have the same
* length, elements and order. Additionally, the Pool must have at least one registered token.
*/
function _validateTokensAndGetBalances(bytes32 poolId, IERC20[] memory expectedTokens)
private
view
returns (bytes32[] memory)
{
(IERC20[] memory actualTokens, bytes32[] memory balances) = _getPoolTokens(poolId);
InputHelpers.ensureInputLengthMatch(actualTokens.length, expectedTokens.length);
_require(actualTokens.length > 0, Errors.POOL_NO_TOKENS);
for (uint256 i = 0; i < actualTokens.length; ++i) {
_require(actualTokens[i] == expectedTokens[i], Errors.TOKENS_MISMATCH);
}
return balances;
}
/**
* @dev Casts an array of uint256 to int256, setting the sign of the result according to the `positive` flag,
* without checking whether the values fit in the signed 256 bit range.
*/
function _unsafeCastToInt256(uint256[] memory values, bool positive)
private
pure
returns (int256[] memory signedValues)
{
signedValues = new int256[](values.length);
for (uint256 i = 0; i < values.length; i++) {
signedValues[i] = positive ? int256(values[i]) : -int256(values[i]);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../../lib/openzeppelin/IERC20.sol";
import "./IVault.sol";
interface IPoolSwapStructs {
// This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and
// IMinimalSwapInfoPool.
//
// This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or
// 'given out') which indicates whether or not the amount sent by the pool is known.
//
// The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take
// in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`.
//
// All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in
// some Pools.
//
// `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than
// one Pool.
//
// The meaning of `lastChangeBlock` depends on the Pool specialization:
// - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total
// balance.
// - General: the last block in which *any* of the Pool's registered tokens changed its total balance.
//
// `from` is the origin address for the funds the Pool receives, and `to` is the destination address
// where the Pool sends the outgoing tokens.
//
// `userData` is extra data provided by the caller - typically a signature from a trusted party.
struct SwapRequest {
IVault.SwapKind kind;
IERC20 tokenIn;
IERC20 tokenOut;
uint256 amount;
// Misc data
bytes32 poolId;
uint256 lastChangeBlock;
address from;
address to;
bytes userData;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IBasePool.sol";
/**
* @dev IPools with the General specialization setting should implement this interface.
*
* This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool.
* Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will
* grant to the pool in a 'given out' swap.
*
* This can often be implemented by a `view` function, since many pricing algorithms don't need to track state
* changes in swaps. However, contracts implementing this in non-view functions should check that the caller is
* indeed the Vault.
*/
interface IGeneralPool is IBasePool {
function onSwap(
SwapRequest memory swapRequest,
uint256[] memory balances,
uint256 indexIn,
uint256 indexOut
) external returns (uint256 amount);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IBasePool.sol";
/**
* @dev Pool contracts with the MinimalSwapInfo or TwoToken specialization settings should implement this interface.
*
* This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool.
* Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will grant
* to the pool in a 'given out' swap.
*
* This can often be implemented by a `view` function, since many pricing algorithms don't need to track state
* changes in swaps. However, contracts implementing this in non-view functions should check that the caller is
* indeed the Vault.
*/
interface IMinimalSwapInfoPool is IBasePool {
function onSwap(
SwapRequest memory swapRequest,
uint256 currentBalanceTokenIn,
uint256 currentBalanceTokenOut
) external returns (uint256 amount);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../../lib/math/Math.sol";
// This library is used to create a data structure that represents a token's balance for a Pool. 'cash' is how many
// tokens the Pool has sitting inside of the Vault. 'managed' is how many tokens were withdrawn from the Vault by the
// Pool's Asset Manager. 'total' is the sum of these two, and represents the Pool's total token balance, including
// tokens that are *not* inside of the Vault.
//
// 'cash' is updated whenever tokens enter and exit the Vault, while 'managed' is only updated if the reason tokens are
// moving is due to an Asset Manager action. This is reflected in the different methods available: 'increaseCash'
// and 'decreaseCash' for swaps and add/remove liquidity events, and 'cashToManaged' and 'managedToCash' for events
// transferring funds to and from the Asset Manager.
//
// The Vault disallows the Pool's 'cash' from becoming negative. In other words, it can never use any tokens that are
// not inside the Vault.
//
// One of the goals of this library is to store the entire token balance in a single storage slot, which is why we use
// 112 bit unsigned integers for 'cash' and 'managed'. For consistency, we also disallow any combination of 'cash' and
// 'managed' that yields a 'total' that doesn't fit in 112 bits.
//
// The remaining 32 bits of the slot are used to store the most recent block when the total balance changed. This
// can be used to implement price oracles that are resilient to 'sandwich' attacks.
//
// We could use a Solidity struct to pack these three values together in a single storage slot, but unfortunately
// Solidity only allows for structs to live in either storage, calldata or memory. Because a memory struct still takes
// up a slot in the stack (to store its memory location), and because the entire balance fits in a single stack slot
// (two 112 bit values plus the 32 bit block), using memory is strictly less gas performant. Therefore, we do manual
// packing and unpacking.
//
// Since we cannot define new types, we rely on bytes32 to represent these values instead, as it doesn't have any
// associated arithmetic operations and therefore reduces the chance of misuse.
library BalanceAllocation {
using Math for uint256;
// The 'cash' portion of the balance is stored in the least significant 112 bits of a 256 bit word, while the
// 'managed' part uses the following 112 bits. The most significant 32 bits are used to store the block
/**
* @dev Returns the total amount of Pool tokens, including those that are not currently in the Vault ('managed').
*/
function total(bytes32 balance) internal pure returns (uint256) {
// Since 'cash' and 'managed' are 112 bit values, we don't need checked arithmetic. Additionally, `toBalance`
// ensures that 'total' always fits in 112 bits.
return cash(balance) + managed(balance);
}
/**
* @dev Returns the amount of Pool tokens currently in the Vault.
*/
function cash(bytes32 balance) internal pure returns (uint256) {
uint256 mask = 2**(112) - 1;
return uint256(balance) & mask;
}
/**
* @dev Returns the amount of Pool tokens that are being managed by an Asset Manager.
*/
function managed(bytes32 balance) internal pure returns (uint256) {
uint256 mask = 2**(112) - 1;
return uint256(balance >> 112) & mask;
}
/**
* @dev Returns the last block when the total balance changed.
*/
function lastChangeBlock(bytes32 balance) internal pure returns (uint256) {
uint256 mask = 2**(32) - 1;
return uint256(balance >> 224) & mask;
}
/**
* @dev Returns the difference in 'managed' between two balances.
*/
function managedDelta(bytes32 newBalance, bytes32 oldBalance) internal pure returns (int256) {
// Because `managed` is a 112 bit value, we can safely perform unchecked arithmetic in 256 bits.
return int256(managed(newBalance)) - int256(managed(oldBalance));
}
/**
* @dev Returns the total balance for each entry in `balances`, as well as the latest block when the total
* balance of *any* of them last changed.
*/
function totalsAndLastChangeBlock(bytes32[] memory balances)
internal
pure
returns (
uint256[] memory results,
uint256 lastChangeBlock_ // Avoid shadowing
)
{
results = new uint256[](balances.length);
lastChangeBlock_ = 0;
for (uint256 i = 0; i < results.length; i++) {
bytes32 balance = balances[i];
results[i] = total(balance);
lastChangeBlock_ = Math.max(lastChangeBlock_, lastChangeBlock(balance));
}
}
/**
* @dev Returns true if `balance`'s 'total' balance is zero. Costs less gas than computing 'total' and comparing
* with zero.
*/
function isZero(bytes32 balance) internal pure returns (bool) {
// We simply need to check the least significant 224 bytes of the word: the block does not affect this.
uint256 mask = 2**(224) - 1;
return (uint256(balance) & mask) == 0;
}
/**
* @dev Returns true if `balance`'s 'total' balance is not zero. Costs less gas than computing 'total' and comparing
* with zero.
*/
function isNotZero(bytes32 balance) internal pure returns (bool) {
return !isZero(balance);
}
/**
* @dev Packs together `cash` and `managed` amounts with a block to create a balance value.
*
* For consistency, this also checks that the sum of `cash` and `managed` (`total`) fits in 112 bits.
*/
function toBalance(
uint256 _cash,
uint256 _managed,
uint256 _blockNumber
) internal pure returns (bytes32) {
uint256 _total = _cash + _managed;
// Since both 'cash' and 'managed' are positive integers, by checking that their sum ('total') fits in 112 bits
// we are also indirectly checking that both 'cash' and 'managed' themselves fit in 112 bits.
_require(_total >= _cash && _total < 2**112, Errors.BALANCE_TOTAL_OVERFLOW);
// We assume the block fits in 32 bits - this is expected to hold for at least a few decades.
return _pack(_cash, _managed, _blockNumber);
}
/**
* @dev Increases a Pool's 'cash' (and therefore its 'total'). Called when Pool tokens are sent to the Vault (except
* for Asset Manager deposits).
*
* Updates the last total balance change block, even if `amount` is zero.
*/
function increaseCash(bytes32 balance, uint256 amount) internal view returns (bytes32) {
uint256 newCash = cash(balance).add(amount);
uint256 currentManaged = managed(balance);
uint256 newLastChangeBlock = block.number;
return toBalance(newCash, currentManaged, newLastChangeBlock);
}
/**
* @dev Decreases a Pool's 'cash' (and therefore its 'total'). Called when Pool tokens are sent from the Vault
* (except for Asset Manager withdrawals).
*
* Updates the last total balance change block, even if `amount` is zero.
*/
function decreaseCash(bytes32 balance, uint256 amount) internal view returns (bytes32) {
uint256 newCash = cash(balance).sub(amount);
uint256 currentManaged = managed(balance);
uint256 newLastChangeBlock = block.number;
return toBalance(newCash, currentManaged, newLastChangeBlock);
}
/**
* @dev Moves 'cash' into 'managed', leaving 'total' unchanged. Called when an Asset Manager withdraws Pool tokens
* from the Vault.
*/
function cashToManaged(bytes32 balance, uint256 amount) internal pure returns (bytes32) {
uint256 newCash = cash(balance).sub(amount);
uint256 newManaged = managed(balance).add(amount);
uint256 currentLastChangeBlock = lastChangeBlock(balance);
return toBalance(newCash, newManaged, currentLastChangeBlock);
}
/**
* @dev Moves 'managed' into 'cash', leaving 'total' unchanged. Called when an Asset Manager deposits Pool tokens
* into the Vault.
*/
function managedToCash(bytes32 balance, uint256 amount) internal pure returns (bytes32) {
uint256 newCash = cash(balance).add(amount);
uint256 newManaged = managed(balance).sub(amount);
uint256 currentLastChangeBlock = lastChangeBlock(balance);
return toBalance(newCash, newManaged, currentLastChangeBlock);
}
/**
* @dev Sets 'managed' balance to an arbitrary value, changing 'total'. Called when the Asset Manager reports
* profits or losses. It's the Manager's responsibility to provide a meaningful value.
*
* Updates the last total balance change block, even if `newManaged` is equal to the current 'managed' value.
*/
function setManaged(bytes32 balance, uint256 newManaged) internal view returns (bytes32) {
uint256 currentCash = cash(balance);
uint256 newLastChangeBlock = block.number;
return toBalance(currentCash, newManaged, newLastChangeBlock);
}
// Alternative mode for Pools with the Two Token specialization setting
// Instead of storing cash and external for each 'token in' a single storage slot, Two Token Pools store the cash
// for both tokens in the same slot, and the managed for both in another one. This reduces the gas cost for swaps,
// because the only slot that needs to be updated is the one with the cash. However, it also means that managing
// balances is more cumbersome, as both tokens need to be read/written at the same time.
//
// The field with both cash balances packed is called sharedCash, and the one with external amounts is called
// sharedManaged. These two are collectively called the 'shared' balance fields. In both of these, the portion
// that corresponds to token A is stored in the least significant 112 bits of a 256 bit word, while token B's part
// uses the next least significant 112 bits.
//
// Because only cash is written to during a swap, we store the last total balance change block with the
// packed cash fields. Typically Pools have a distinct block per token: in the case of Two Token Pools they
// are the same.
/**
* @dev Extracts the part of the balance that corresponds to token A. This function can be used to decode both
* shared cash and managed balances.
*/
function _decodeBalanceA(bytes32 sharedBalance) private pure returns (uint256) {
uint256 mask = 2**(112) - 1;
return uint256(sharedBalance) & mask;
}
/**
* @dev Extracts the part of the balance that corresponds to token B. This function can be used to decode both
* shared cash and managed balances.
*/
function _decodeBalanceB(bytes32 sharedBalance) private pure returns (uint256) {
uint256 mask = 2**(112) - 1;
return uint256(sharedBalance >> 112) & mask;
}
// To decode the last balance change block, we can simply use the `blockNumber` function.
/**
* @dev Unpacks the shared token A and token B cash and managed balances into the balance for token A.
*/
function fromSharedToBalanceA(bytes32 sharedCash, bytes32 sharedManaged) internal pure returns (bytes32) {
// Note that we extract the block from the sharedCash field, which is the one that is updated by swaps.
// Both token A and token B use the same block
return toBalance(_decodeBalanceA(sharedCash), _decodeBalanceA(sharedManaged), lastChangeBlock(sharedCash));
}
/**
* @dev Unpacks the shared token A and token B cash and managed balances into the balance for token B.
*/
function fromSharedToBalanceB(bytes32 sharedCash, bytes32 sharedManaged) internal pure returns (bytes32) {
// Note that we extract the block from the sharedCash field, which is the one that is updated by swaps.
// Both token A and token B use the same block
return toBalance(_decodeBalanceB(sharedCash), _decodeBalanceB(sharedManaged), lastChangeBlock(sharedCash));
}
/**
* @dev Returns the sharedCash shared field, given the current balances for token A and token B.
*/
function toSharedCash(bytes32 tokenABalance, bytes32 tokenBBalance) internal pure returns (bytes32) {
// Both balances are assigned the same block Since it is possible a single one of them has changed (for
// example, in an Asset Manager update), we keep the latest (largest) one.
uint32 newLastChangeBlock = uint32(Math.max(lastChangeBlock(tokenABalance), lastChangeBlock(tokenBBalance)));
return _pack(cash(tokenABalance), cash(tokenBBalance), newLastChangeBlock);
}
/**
* @dev Returns the sharedManaged shared field, given the current balances for token A and token B.
*/
function toSharedManaged(bytes32 tokenABalance, bytes32 tokenBBalance) internal pure returns (bytes32) {
// We don't bother storing a last change block, as it is read from the shared cash field.
return _pack(managed(tokenABalance), managed(tokenBBalance), 0);
}
// Shared functions
/**
* @dev Packs together two uint112 and one uint32 into a bytes32
*/
function _pack(
uint256 _leastSignificant,
uint256 _midSignificant,
uint256 _mostSignificant
) private pure returns (bytes32) {
return bytes32((_mostSignificant << 224) + (_midSignificant << 112) + _leastSignificant);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/helpers/BalancerErrors.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "./AssetManagers.sol";
import "./PoolRegistry.sol";
import "./balances/BalanceAllocation.sol";
abstract contract PoolTokens is ReentrancyGuard, PoolRegistry, AssetManagers {
using BalanceAllocation for bytes32;
using BalanceAllocation for bytes32[];
function registerTokens(
bytes32 poolId,
IERC20[] memory tokens,
address[] memory assetManagers
) external override nonReentrant whenNotPaused onlyPool(poolId) {
InputHelpers.ensureInputLengthMatch(tokens.length, assetManagers.length);
// Validates token addresses and assigns Asset Managers
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
_require(token != IERC20(0), Errors.INVALID_TOKEN);
_poolAssetManagers[poolId][token] = assetManagers[i];
}
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
_require(tokens.length == 2, Errors.TOKENS_LENGTH_MUST_BE_2);
_registerTwoTokenPoolTokens(poolId, tokens[0], tokens[1]);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
_registerMinimalSwapInfoPoolTokens(poolId, tokens);
} else {
// PoolSpecialization.GENERAL
_registerGeneralPoolTokens(poolId, tokens);
}
emit TokensRegistered(poolId, tokens, assetManagers);
}
function deregisterTokens(bytes32 poolId, IERC20[] memory tokens)
external
override
nonReentrant
whenNotPaused
onlyPool(poolId)
{
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
_require(tokens.length == 2, Errors.TOKENS_LENGTH_MUST_BE_2);
_deregisterTwoTokenPoolTokens(poolId, tokens[0], tokens[1]);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
_deregisterMinimalSwapInfoPoolTokens(poolId, tokens);
} else {
// PoolSpecialization.GENERAL
_deregisterGeneralPoolTokens(poolId, tokens);
}
// The deregister calls above ensure the total token balance is zero. Therefore it is now safe to remove any
// associated Asset Managers, since they hold no Pool balance.
for (uint256 i = 0; i < tokens.length; ++i) {
delete _poolAssetManagers[poolId][tokens[i]];
}
emit TokensDeregistered(poolId, tokens);
}
function getPoolTokens(bytes32 poolId)
external
view
override
withRegisteredPool(poolId)
returns (
IERC20[] memory tokens,
uint256[] memory balances,
uint256 lastChangeBlock
)
{
bytes32[] memory rawBalances;
(tokens, rawBalances) = _getPoolTokens(poolId);
(balances, lastChangeBlock) = rawBalances.totalsAndLastChangeBlock();
}
function getPoolTokenInfo(bytes32 poolId, IERC20 token)
external
view
override
withRegisteredPool(poolId)
returns (
uint256 cash,
uint256 managed,
uint256 lastChangeBlock,
address assetManager
)
{
bytes32 balance;
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
balance = _getTwoTokenPoolBalance(poolId, token);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
balance = _getMinimalSwapInfoPoolBalance(poolId, token);
} else {
// PoolSpecialization.GENERAL
balance = _getGeneralPoolBalance(poolId, token);
}
cash = balance.cash();
managed = balance.managed();
lastChangeBlock = balance.lastChangeBlock();
assetManager = _poolAssetManagers[poolId][token];
}
/**
* @dev Returns all of `poolId`'s registered tokens, along with their raw balances.
*/
function _getPoolTokens(bytes32 poolId) internal view returns (IERC20[] memory tokens, bytes32[] memory balances) {
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
return _getTwoTokenPoolTokens(poolId);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
return _getMinimalSwapInfoPoolTokens(poolId);
} else {
// PoolSpecialization.GENERAL
return _getGeneralPoolTokens(poolId);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/helpers/BalancerErrors.sol";
import "../lib/math/Math.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeCast.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./AssetTransfersHandler.sol";
import "./VaultAuthorization.sol";
/**
* Implement User Balance interactions, which combine Internal Balance and using the Vault's ERC20 allowance.
*
* Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later
* transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination
* when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced
* gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.
*
* Internal Balance management features batching, which means a single contract call can be used to perform multiple
* operations of different kinds, with different senders and recipients, at once.
*/
abstract contract UserBalance is ReentrancyGuard, AssetTransfersHandler, VaultAuthorization {
using Math for uint256;
using SafeCast for uint256;
using SafeERC20 for IERC20;
// Internal Balance for each token, for each account.
mapping(address => mapping(IERC20 => uint256)) private _internalTokenBalance;
function getInternalBalance(address user, IERC20[] memory tokens)
external
view
override
returns (uint256[] memory balances)
{
balances = new uint256[](tokens.length);
for (uint256 i = 0; i < tokens.length; i++) {
balances[i] = _getInternalBalance(user, tokens[i]);
}
}
function manageUserBalance(UserBalanceOp[] memory ops) external payable override nonReentrant {
// We need to track how much of the received ETH was used and wrapped into WETH to return any excess.
uint256 ethWrapped = 0;
// Cache for these checks so we only perform them once (if at all).
bool checkedCallerIsRelayer = false;
bool checkedNotPaused = false;
for (uint256 i = 0; i < ops.length; i++) {
UserBalanceOpKind kind;
IAsset asset;
uint256 amount;
address sender;
address payable recipient;
// This destructuring by calling `_validateUserBalanceOp` seems odd, but results in reduced bytecode size.
(kind, asset, amount, sender, recipient, checkedCallerIsRelayer) = _validateUserBalanceOp(
ops[i],
checkedCallerIsRelayer
);
if (kind == UserBalanceOpKind.WITHDRAW_INTERNAL) {
// Internal Balance withdrawals can always be performed by an authorized account.
_withdrawFromInternalBalance(asset, sender, recipient, amount);
} else {
// All other operations are blocked if the contract is paused.
// We cache the result of the pause check and skip it for other operations in this same transaction
// (if any).
if (!checkedNotPaused) {
_ensureNotPaused();
checkedNotPaused = true;
}
if (kind == UserBalanceOpKind.DEPOSIT_INTERNAL) {
_depositToInternalBalance(asset, sender, recipient, amount);
// Keep track of all ETH wrapped into WETH as part of a deposit.
if (_isETH(asset)) {
ethWrapped = ethWrapped.add(amount);
}
} else {
// Transfers don't support ETH.
_require(!_isETH(asset), Errors.CANNOT_USE_ETH_SENTINEL);
IERC20 token = _asIERC20(asset);
if (kind == UserBalanceOpKind.TRANSFER_INTERNAL) {
_transferInternalBalance(token, sender, recipient, amount);
} else {
// TRANSFER_EXTERNAL
_transferToExternalBalance(token, sender, recipient, amount);
}
}
}
}
// Handle any remaining ETH.
_handleRemainingEth(ethWrapped);
}
function _depositToInternalBalance(
IAsset asset,
address sender,
address recipient,
uint256 amount
) private {
_increaseInternalBalance(recipient, _translateToIERC20(asset), amount);
_receiveAsset(asset, amount, sender, false);
}
function _withdrawFromInternalBalance(
IAsset asset,
address sender,
address payable recipient,
uint256 amount
) private {
// A partial decrease of Internal Balance is disallowed: `sender` must have the full `amount`.
_decreaseInternalBalance(sender, _translateToIERC20(asset), amount, false);
_sendAsset(asset, amount, recipient, false);
}
function _transferInternalBalance(
IERC20 token,
address sender,
address recipient,
uint256 amount
) private {
// A partial decrease of Internal Balance is disallowed: `sender` must have the full `amount`.
_decreaseInternalBalance(sender, token, amount, false);
_increaseInternalBalance(recipient, token, amount);
}
function _transferToExternalBalance(
IERC20 token,
address sender,
address recipient,
uint256 amount
) private {
if (amount > 0) {
token.safeTransferFrom(sender, recipient, amount);
emit ExternalBalanceTransfer(token, sender, recipient, amount);
}
}
/**
* @dev Increases `account`'s Internal Balance for `token` by `amount`.
*/
function _increaseInternalBalance(
address account,
IERC20 token,
uint256 amount
) internal override {
uint256 currentBalance = _getInternalBalance(account, token);
uint256 newBalance = currentBalance.add(amount);
_setInternalBalance(account, token, newBalance, amount.toInt256());
}
/**
* @dev Decreases `account`'s Internal Balance for `token` by `amount`. If `allowPartial` is true, this function
* doesn't revert if `account` doesn't have enough balance, and sets it to zero and returns the deducted amount
* instead.
*/
function _decreaseInternalBalance(
address account,
IERC20 token,
uint256 amount,
bool allowPartial
) internal override returns (uint256 deducted) {
uint256 currentBalance = _getInternalBalance(account, token);
_require(allowPartial || (currentBalance >= amount), Errors.INSUFFICIENT_INTERNAL_BALANCE);
deducted = Math.min(currentBalance, amount);
// By construction, `deducted` is lower or equal to `currentBalance`, so we don't need to use checked
// arithmetic.
uint256 newBalance = currentBalance - deducted;
_setInternalBalance(account, token, newBalance, -(deducted.toInt256()));
}
/**
* @dev Sets `account`'s Internal Balance for `token` to `newBalance`.
*
* Emits an `InternalBalanceChanged` event. This event includes `delta`, which is the amount the balance increased
* (if positive) or decreased (if negative). To avoid reading the current balance in order to compute the delta,
* this function relies on the caller providing it directly.
*/
function _setInternalBalance(
address account,
IERC20 token,
uint256 newBalance,
int256 delta
) private {
_internalTokenBalance[account][token] = newBalance;
emit InternalBalanceChanged(account, token, delta);
}
/**
* @dev Returns `account`'s Internal Balance for `token`.
*/
function _getInternalBalance(address account, IERC20 token) internal view returns (uint256) {
return _internalTokenBalance[account][token];
}
/**
* @dev Destructures a User Balance operation, validating that the contract caller is allowed to perform it.
*/
function _validateUserBalanceOp(UserBalanceOp memory op, bool checkedCallerIsRelayer)
private
view
returns (
UserBalanceOpKind,
IAsset,
uint256,
address,
address payable,
bool
)
{
// The only argument we need to validate is `sender`, which can only be either the contract caller, or a
// relayer approved by `sender`.
address sender = op.sender;
if (sender != msg.sender) {
// We need to check both that the contract caller is a relayer, and that `sender` approved them.
// Because the relayer check is global (i.e. independent of `sender`), we cache that result and skip it for
// other operations in this same transaction (if any).
if (!checkedCallerIsRelayer) {
_authenticateCaller();
checkedCallerIsRelayer = true;
}
_require(_hasApprovedRelayer(sender, msg.sender), Errors.USER_DOESNT_ALLOW_RELAYER);
}
return (op.kind, op.asset, op.amount, sender, op.recipient, checkedCallerIsRelayer);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IVault.sol";
import "./IPoolSwapStructs.sol";
/**
* @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not
* the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from
* either IGeneralPool or IMinimalSwapInfoPool
*/
interface IBasePool is IPoolSwapStructs {
/**
* @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of
* each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault.
* The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect
* the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`.
*
* Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join.
*
* `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account
* designated to receive any benefits (typically pool shares). `currentBalances` contains the total balances
* for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
*
* `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
* balance.
*
* `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
* join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
*
* Contracts implementing this function should check that the caller is indeed the Vault before performing any
* state-changing operations, such as minting pool shares.
*/
function onJoinPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts);
/**
* @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many
* tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes
* to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`,
* as well as collect the reported amount in protocol fees, which the Pool should calculate based on
* `protocolSwapFeePercentage`.
*
* Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share.
*
* `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account
* to which the Vault will send the proceeds. `currentBalances` contains the total token balances for each token
* the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
*
* `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
* balance.
*
* `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
* exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
*
* Contracts implementing this function should check that the caller is indeed the Vault before performing any
* state-changing operations, such as burning pool shares.
*/
function onExitPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/math/Math.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/helpers/InputHelpers.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "./UserBalance.sol";
import "./balances/BalanceAllocation.sol";
import "./balances/GeneralPoolsBalance.sol";
import "./balances/MinimalSwapInfoPoolsBalance.sol";
import "./balances/TwoTokenPoolsBalance.sol";
abstract contract AssetManagers is
ReentrancyGuard,
GeneralPoolsBalance,
MinimalSwapInfoPoolsBalance,
TwoTokenPoolsBalance
{
using Math for uint256;
using SafeERC20 for IERC20;
// Stores the Asset Manager for each token of each Pool.
mapping(bytes32 => mapping(IERC20 => address)) internal _poolAssetManagers;
function managePoolBalance(PoolBalanceOp[] memory ops) external override nonReentrant whenNotPaused {
// This variable could be declared inside the loop, but that causes the compiler to allocate memory on each
// loop iteration, increasing gas costs.
PoolBalanceOp memory op;
for (uint256 i = 0; i < ops.length; ++i) {
// By indexing the array only once, we don't spend extra gas in the same bounds check.
op = ops[i];
bytes32 poolId = op.poolId;
_ensureRegisteredPool(poolId);
IERC20 token = op.token;
_require(_isTokenRegistered(poolId, token), Errors.TOKEN_NOT_REGISTERED);
_require(_poolAssetManagers[poolId][token] == msg.sender, Errors.SENDER_NOT_ASSET_MANAGER);
PoolBalanceOpKind kind = op.kind;
uint256 amount = op.amount;
(int256 cashDelta, int256 managedDelta) = _performPoolManagementOperation(kind, poolId, token, amount);
emit PoolBalanceManaged(poolId, msg.sender, token, cashDelta, managedDelta);
}
}
/**
* @dev Performs the `kind` Asset Manager operation on a Pool.
*
* Withdrawals will transfer `amount` tokens to the caller, deposits will transfer `amount` tokens from the caller,
* and updates will set the managed balance to `amount`.
*
* Returns a tuple with the 'cash' and 'managed' balance deltas as a result of this call.
*/
function _performPoolManagementOperation(
PoolBalanceOpKind kind,
bytes32 poolId,
IERC20 token,
uint256 amount
) private returns (int256, int256) {
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (kind == PoolBalanceOpKind.WITHDRAW) {
return _withdrawPoolBalance(poolId, specialization, token, amount);
} else if (kind == PoolBalanceOpKind.DEPOSIT) {
return _depositPoolBalance(poolId, specialization, token, amount);
} else {
// PoolBalanceOpKind.UPDATE
return _updateManagedBalance(poolId, specialization, token, amount);
}
}
/**
* @dev Moves `amount` tokens from a Pool's 'cash' to 'managed' balance, and transfers them to the caller.
*
* Returns the 'cash' and 'managed' balance deltas as a result of this call, which will be complementary.
*/
function _withdrawPoolBalance(
bytes32 poolId,
PoolSpecialization specialization,
IERC20 token,
uint256 amount
) private returns (int256 cashDelta, int256 managedDelta) {
if (specialization == PoolSpecialization.TWO_TOKEN) {
_twoTokenPoolCashToManaged(poolId, token, amount);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
_minimalSwapInfoPoolCashToManaged(poolId, token, amount);
} else {
// PoolSpecialization.GENERAL
_generalPoolCashToManaged(poolId, token, amount);
}
if (amount > 0) {
token.safeTransfer(msg.sender, amount);
}
// Since 'cash' and 'managed' are stored as uint112, `amount` is guaranteed to also fit in 112 bits. It will
// therefore always fit in a 256 bit integer.
cashDelta = int256(-amount);
managedDelta = int256(amount);
}
/**
* @dev Moves `amount` tokens from a Pool's 'managed' to 'cash' balance, and transfers them from the caller.
*
* Returns the 'cash' and 'managed' balance deltas as a result of this call, which will be complementary.
*/
function _depositPoolBalance(
bytes32 poolId,
PoolSpecialization specialization,
IERC20 token,
uint256 amount
) private returns (int256 cashDelta, int256 managedDelta) {
if (specialization == PoolSpecialization.TWO_TOKEN) {
_twoTokenPoolManagedToCash(poolId, token, amount);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
_minimalSwapInfoPoolManagedToCash(poolId, token, amount);
} else {
// PoolSpecialization.GENERAL
_generalPoolManagedToCash(poolId, token, amount);
}
if (amount > 0) {
token.safeTransferFrom(msg.sender, address(this), amount);
}
// Since 'cash' and 'managed' are stored as uint112, `amount` is guaranteed to also fit in 112 bits. It will
// therefore always fit in a 256 bit integer.
cashDelta = int256(amount);
managedDelta = int256(-amount);
}
/**
* @dev Sets a Pool's 'managed' balance to `amount`.
*
* Returns the 'cash' and 'managed' balance deltas as a result of this call (the 'cash' delta will always be zero).
*/
function _updateManagedBalance(
bytes32 poolId,
PoolSpecialization specialization,
IERC20 token,
uint256 amount
) private returns (int256 cashDelta, int256 managedDelta) {
if (specialization == PoolSpecialization.TWO_TOKEN) {
managedDelta = _setTwoTokenPoolManagedBalance(poolId, token, amount);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
managedDelta = _setMinimalSwapInfoPoolManagedBalance(poolId, token, amount);
} else {
// PoolSpecialization.GENERAL
managedDelta = _setGeneralPoolManagedBalance(poolId, token, amount);
}
cashDelta = 0;
}
/**
* @dev Returns true if `token` is registered for `poolId`.
*/
function _isTokenRegistered(bytes32 poolId, IERC20 token) private view returns (bool) {
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
return _isTwoTokenPoolTokenRegistered(poolId, token);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
return _isMinimalSwapInfoPoolTokenRegistered(poolId, token);
} else {
// PoolSpecialization.GENERAL
return _isGeneralPoolTokenRegistered(poolId, token);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/helpers/BalancerErrors.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "./VaultAuthorization.sol";
/**
* @dev Maintains the Pool ID data structure, implements Pool ID creation and registration, and defines useful modifiers
* and helper functions for ensuring correct behavior when working with Pools.
*/
abstract contract PoolRegistry is ReentrancyGuard, VaultAuthorization {
// Each pool is represented by their unique Pool ID. We use `bytes32` for them, for lack of a way to define new
// types.
mapping(bytes32 => bool) private _isPoolRegistered;
// We keep an increasing nonce to make Pool IDs unique. It is interpreted as a `uint80`, but storing it as a
// `uint256` results in reduced bytecode on reads and writes due to the lack of masking.
uint256 private _nextPoolNonce;
/**
* @dev Reverts unless `poolId` corresponds to a registered Pool.
*/
modifier withRegisteredPool(bytes32 poolId) {
_ensureRegisteredPool(poolId);
_;
}
/**
* @dev Reverts unless `poolId` corresponds to a registered Pool, and the caller is the Pool's contract.
*/
modifier onlyPool(bytes32 poolId) {
_ensurePoolIsSender(poolId);
_;
}
/**
* @dev Reverts unless `poolId` corresponds to a registered Pool.
*/
function _ensureRegisteredPool(bytes32 poolId) internal view {
_require(_isPoolRegistered[poolId], Errors.INVALID_POOL_ID);
}
/**
* @dev Reverts unless `poolId` corresponds to a registered Pool, and the caller is the Pool's contract.
*/
function _ensurePoolIsSender(bytes32 poolId) private view {
_ensureRegisteredPool(poolId);
_require(msg.sender == _getPoolAddress(poolId), Errors.CALLER_NOT_POOL);
}
function registerPool(PoolSpecialization specialization)
external
override
nonReentrant
whenNotPaused
returns (bytes32)
{
// Each Pool is assigned a unique ID based on an incrementing nonce. This assumes there will never be more than
// 2**80 Pools, and the nonce will not overflow.
bytes32 poolId = _toPoolId(msg.sender, specialization, uint80(_nextPoolNonce));
_require(!_isPoolRegistered[poolId], Errors.INVALID_POOL_ID); // Should never happen as Pool IDs are unique.
_isPoolRegistered[poolId] = true;
_nextPoolNonce += 1;
// Note that msg.sender is the pool's contract
emit PoolRegistered(poolId, msg.sender, specialization);
return poolId;
}
function getPool(bytes32 poolId)
external
view
override
withRegisteredPool(poolId)
returns (address, PoolSpecialization)
{
return (_getPoolAddress(poolId), _getPoolSpecialization(poolId));
}
/**
* @dev Creates a Pool ID.
*
* These are deterministically created by packing the Pool's contract address and its specialization setting into
* the ID. This saves gas by making this data easily retrievable from a Pool ID with no storage accesses.
*
* Since a single contract can register multiple Pools, a unique nonce must be provided to ensure Pool IDs are
* unique.
*
* Pool IDs have the following layout:
* | 20 bytes pool contract address | 2 bytes specialization setting | 10 bytes nonce |
* MSB LSB
*
* 2 bytes for the specialization setting is a bit overkill: there only three of them, which means two bits would
* suffice. However, there's nothing else of interest to store in this extra space.
*/
function _toPoolId(
address pool,
PoolSpecialization specialization,
uint80 nonce
) internal pure returns (bytes32) {
bytes32 serialized;
serialized |= bytes32(uint256(nonce));
serialized |= bytes32(uint256(specialization)) << (10 * 8);
serialized |= bytes32(uint256(pool)) << (12 * 8);
return serialized;
}
/**
* @dev Returns the address of a Pool's contract.
*
* Due to how Pool IDs are created, this is done with no storage accesses and costs little gas.
*/
function _getPoolAddress(bytes32 poolId) internal pure returns (address) {
// 12 byte logical shift left to remove the nonce and specialization setting. We don't need to mask,
// since the logical shift already sets the upper bits to zero.
return address(uint256(poolId) >> (12 * 8));
}
/**
* @dev Returns the specialization setting of a Pool.
*
* Due to how Pool IDs are created, this is done with no storage accesses and costs little gas.
*/
function _getPoolSpecialization(bytes32 poolId) internal pure returns (PoolSpecialization specialization) {
// 10 byte logical shift left to remove the nonce, followed by a 2 byte mask to remove the address.
uint256 value = uint256(poolId >> (10 * 8)) & (2**(2 * 8) - 1);
// Casting a value into an enum results in a runtime check that reverts unless the value is within the enum's
// range. Passing an invalid Pool ID to this function would then result in an obscure revert with no reason
// string: we instead perform the check ourselves to help in error diagnosis.
// There are three Pool specialization settings: general, minimal swap info and two tokens, which correspond to
// values 0, 1 and 2.
_require(value < 3, Errors.INVALID_POOL_ID);
// Because we have checked that `value` is within the enum range, we can use assembly to skip the runtime check.
// solhint-disable-next-line no-inline-assembly
assembly {
specialization := value
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../../lib/helpers/BalancerErrors.sol";
import "../../lib/openzeppelin/EnumerableMap.sol";
import "../../lib/openzeppelin/IERC20.sol";
import "./BalanceAllocation.sol";
abstract contract GeneralPoolsBalance {
using BalanceAllocation for bytes32;
using EnumerableMap for EnumerableMap.IERC20ToBytes32Map;
// Data for Pools with the General specialization setting
//
// These Pools use the IGeneralPool interface, which means the Vault must query the balance for *all* of their
// tokens in every swap. If we kept a mapping of token to balance plus a set (array) of tokens, it'd be very gas
// intensive to read all token addresses just to then do a lookup on the balance mapping.
//
// Instead, we use our customized EnumerableMap, which lets us read the N balances in N+1 storage accesses (one for
// each token in the Pool), access the index of any 'token in' a single read (required for the IGeneralPool call),
// and update an entry's value given its index.
// Map of token -> balance pairs for each Pool with this specialization. Many functions rely on storage pointers to
// a Pool's EnumerableMap to save gas when computing storage slots.
mapping(bytes32 => EnumerableMap.IERC20ToBytes32Map) internal _generalPoolsBalances;
/**
* @dev Registers a list of tokens in a General Pool.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*
* Requirements:
*
* - `tokens` must not be registered in the Pool
* - `tokens` must not contain duplicates
*/
function _registerGeneralPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
for (uint256 i = 0; i < tokens.length; ++i) {
// EnumerableMaps require an explicit initial value when creating a key-value pair: we use zero, the same
// value that is found in uninitialized storage, which corresponds to an empty balance.
bool added = poolBalances.set(tokens[i], 0);
_require(added, Errors.TOKEN_ALREADY_REGISTERED);
}
}
/**
* @dev Deregisters a list of tokens in a General Pool.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*
* Requirements:
*
* - `tokens` must be registered in the Pool
* - `tokens` must have zero balance in the Vault
* - `tokens` must not contain duplicates
*/
function _deregisterGeneralPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
bytes32 currentBalance = _getGeneralPoolBalance(poolBalances, token);
_require(currentBalance.isZero(), Errors.NONZERO_TOKEN_BALANCE);
// We don't need to check remove's return value, since _getGeneralPoolBalance already checks that the token
// was registered.
poolBalances.remove(token);
}
}
/**
* @dev Sets the balances of a General Pool's tokens to `balances`.
*
* WARNING: this assumes `balances` has the same length and order as the Pool's tokens.
*/
function _setGeneralPoolBalances(bytes32 poolId, bytes32[] memory balances) internal {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
for (uint256 i = 0; i < balances.length; ++i) {
// Since we assume all balances are properly ordered, we can simply use `unchecked_setAt` to avoid one less
// storage read per token.
poolBalances.unchecked_setAt(i, balances[i]);
}
}
/**
* @dev Transforms `amount` of `token`'s balance in a General Pool from cash into managed.
*
* This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is
* registered for that Pool.
*/
function _generalPoolCashToManaged(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateGeneralPoolBalance(poolId, token, BalanceAllocation.cashToManaged, amount);
}
/**
* @dev Transforms `amount` of `token`'s balance in a General Pool from managed into cash.
*
* This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is
* registered for that Pool.
*/
function _generalPoolManagedToCash(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateGeneralPoolBalance(poolId, token, BalanceAllocation.managedToCash, amount);
}
/**
* @dev Sets `token`'s managed balance in a General Pool to `amount`.
*
* This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is
* registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _setGeneralPoolManagedBalance(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal returns (int256) {
return _updateGeneralPoolBalance(poolId, token, BalanceAllocation.setManaged, amount);
}
/**
* @dev Sets `token`'s balance in a General Pool to the result of the `mutation` function when called with the
* current balance and `amount`.
*
* This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is
* registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _updateGeneralPoolBalance(
bytes32 poolId,
IERC20 token,
function(bytes32, uint256) returns (bytes32) mutation,
uint256 amount
) private returns (int256) {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
bytes32 currentBalance = _getGeneralPoolBalance(poolBalances, token);
bytes32 newBalance = mutation(currentBalance, amount);
poolBalances.set(token, newBalance);
return newBalance.managedDelta(currentBalance);
}
/**
* @dev Returns an array with all the tokens and balances in a General Pool. The order may change when tokens are
* registered or deregistered.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*/
function _getGeneralPoolTokens(bytes32 poolId)
internal
view
returns (IERC20[] memory tokens, bytes32[] memory balances)
{
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
tokens = new IERC20[](poolBalances.length());
balances = new bytes32[](tokens.length);
for (uint256 i = 0; i < tokens.length; ++i) {
// Because the iteration is bounded by `tokens.length`, which matches the EnumerableMap's length, we can use
// `unchecked_at` as we know `i` is a valid token index, saving storage reads.
(tokens[i], balances[i]) = poolBalances.unchecked_at(i);
}
}
/**
* @dev Returns the balance of a token in a General Pool.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*
* Requirements:
*
* - `token` must be registered in the Pool
*/
function _getGeneralPoolBalance(bytes32 poolId, IERC20 token) internal view returns (bytes32) {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
return _getGeneralPoolBalance(poolBalances, token);
}
/**
* @dev Same as `_getGeneralPoolBalance` but using a Pool's storage pointer, which saves gas in repeated reads and
* writes.
*/
function _getGeneralPoolBalance(EnumerableMap.IERC20ToBytes32Map storage poolBalances, IERC20 token)
private
view
returns (bytes32)
{
return poolBalances.get(token, Errors.TOKEN_NOT_REGISTERED);
}
/**
* @dev Returns true if `token` is registered in a General Pool.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*/
function _isGeneralPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
return poolBalances.contains(token);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../../lib/helpers/BalancerErrors.sol";
import "../../lib/openzeppelin/EnumerableSet.sol";
import "../../lib/openzeppelin/IERC20.sol";
import "./BalanceAllocation.sol";
import "../PoolRegistry.sol";
abstract contract MinimalSwapInfoPoolsBalance is PoolRegistry {
using BalanceAllocation for bytes32;
using EnumerableSet for EnumerableSet.AddressSet;
// Data for Pools with the Minimal Swap Info specialization setting
//
// These Pools use the IMinimalSwapInfoPool interface, and so the Vault must read the balance of the two tokens
// in the swap. The best solution is to use a mapping from token to balance, which lets us read or write any token's
// balance in a single storage access.
//
// We also keep a set of registered tokens. Because tokens with non-zero balance are by definition registered, in
// some balance getters we skip checking for token registration if a non-zero balance is found, saving gas by
// performing a single read instead of two.
mapping(bytes32 => mapping(IERC20 => bytes32)) internal _minimalSwapInfoPoolsBalances;
mapping(bytes32 => EnumerableSet.AddressSet) internal _minimalSwapInfoPoolsTokens;
/**
* @dev Registers a list of tokens in a Minimal Swap Info Pool.
*
* This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting.
*
* Requirements:
*
* - `tokens` must not be registered in the Pool
* - `tokens` must not contain duplicates
*/
function _registerMinimalSwapInfoPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal {
EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId];
for (uint256 i = 0; i < tokens.length; ++i) {
bool added = poolTokens.add(address(tokens[i]));
_require(added, Errors.TOKEN_ALREADY_REGISTERED);
// Note that we don't initialize the balance mapping: the default value of zero corresponds to an empty
// balance.
}
}
/**
* @dev Deregisters a list of tokens in a Minimal Swap Info Pool.
*
* This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting.
*
* Requirements:
*
* - `tokens` must be registered in the Pool
* - `tokens` must have zero balance in the Vault
* - `tokens` must not contain duplicates
*/
function _deregisterMinimalSwapInfoPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal {
EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId];
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
_require(_minimalSwapInfoPoolsBalances[poolId][token].isZero(), Errors.NONZERO_TOKEN_BALANCE);
// For consistency with other Pool specialization settings, we explicitly reset the balance (which may have
// a non-zero last change block).
delete _minimalSwapInfoPoolsBalances[poolId][token];
bool removed = poolTokens.remove(address(token));
_require(removed, Errors.TOKEN_NOT_REGISTERED);
}
}
/**
* @dev Sets the balances of a Minimal Swap Info Pool's tokens to `balances`.
*
* WARNING: this assumes `balances` has the same length and order as the Pool's tokens.
*/
function _setMinimalSwapInfoPoolBalances(
bytes32 poolId,
IERC20[] memory tokens,
bytes32[] memory balances
) internal {
for (uint256 i = 0; i < tokens.length; ++i) {
_minimalSwapInfoPoolsBalances[poolId][tokens[i]] = balances[i];
}
}
/**
* @dev Transforms `amount` of `token`'s balance in a Minimal Swap Info Pool from cash into managed.
*
* This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that
* `token` is registered for that Pool.
*/
function _minimalSwapInfoPoolCashToManaged(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateMinimalSwapInfoPoolBalance(poolId, token, BalanceAllocation.cashToManaged, amount);
}
/**
* @dev Transforms `amount` of `token`'s balance in a Minimal Swap Info Pool from managed into cash.
*
* This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that
* `token` is registered for that Pool.
*/
function _minimalSwapInfoPoolManagedToCash(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateMinimalSwapInfoPoolBalance(poolId, token, BalanceAllocation.managedToCash, amount);
}
/**
* @dev Sets `token`'s managed balance in a Minimal Swap Info Pool to `amount`.
*
* This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that
* `token` is registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _setMinimalSwapInfoPoolManagedBalance(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal returns (int256) {
return _updateMinimalSwapInfoPoolBalance(poolId, token, BalanceAllocation.setManaged, amount);
}
/**
* @dev Sets `token`'s balance in a Minimal Swap Info Pool to the result of the `mutation` function when called with
* the current balance and `amount`.
*
* This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that
* `token` is registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _updateMinimalSwapInfoPoolBalance(
bytes32 poolId,
IERC20 token,
function(bytes32, uint256) returns (bytes32) mutation,
uint256 amount
) internal returns (int256) {
bytes32 currentBalance = _getMinimalSwapInfoPoolBalance(poolId, token);
bytes32 newBalance = mutation(currentBalance, amount);
_minimalSwapInfoPoolsBalances[poolId][token] = newBalance;
return newBalance.managedDelta(currentBalance);
}
/**
* @dev Returns an array with all the tokens and balances in a Minimal Swap Info Pool. The order may change when
* tokens are registered or deregistered.
*
* This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting.
*/
function _getMinimalSwapInfoPoolTokens(bytes32 poolId)
internal
view
returns (IERC20[] memory tokens, bytes32[] memory balances)
{
EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId];
tokens = new IERC20[](poolTokens.length());
balances = new bytes32[](tokens.length);
for (uint256 i = 0; i < tokens.length; ++i) {
// Because the iteration is bounded by `tokens.length`, which matches the EnumerableSet's length, we can use
// `unchecked_at` as we know `i` is a valid token index, saving storage reads.
IERC20 token = IERC20(poolTokens.unchecked_at(i));
tokens[i] = token;
balances[i] = _minimalSwapInfoPoolsBalances[poolId][token];
}
}
/**
* @dev Returns the balance of a token in a Minimal Swap Info Pool.
*
* Requirements:
*
* - `poolId` must be a Minimal Swap Info Pool
* - `token` must be registered in the Pool
*/
function _getMinimalSwapInfoPoolBalance(bytes32 poolId, IERC20 token) internal view returns (bytes32) {
bytes32 balance = _minimalSwapInfoPoolsBalances[poolId][token];
// A non-zero balance guarantees that the token is registered. If zero, we manually check if the token is
// registered in the Pool. Token registration implies that the Pool is registered as well, which lets us save
// gas by not performing the check.
bool tokenRegistered = balance.isNotZero() || _minimalSwapInfoPoolsTokens[poolId].contains(address(token));
if (!tokenRegistered) {
// The token might not be registered because the Pool itself is not registered. We check this to provide a
// more accurate revert reason.
_ensureRegisteredPool(poolId);
_revert(Errors.TOKEN_NOT_REGISTERED);
}
return balance;
}
/**
* @dev Returns true if `token` is registered in a Minimal Swap Info Pool.
*
* This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting.
*/
function _isMinimalSwapInfoPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) {
EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId];
return poolTokens.contains(address(token));
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../../lib/helpers/BalancerErrors.sol";
import "../../lib/openzeppelin/IERC20.sol";
import "./BalanceAllocation.sol";
import "../PoolRegistry.sol";
abstract contract TwoTokenPoolsBalance is PoolRegistry {
using BalanceAllocation for bytes32;
// Data for Pools with the Two Token specialization setting
//
// These are similar to the Minimal Swap Info Pool case (because the Pool only has two tokens, and therefore there
// are only two balances to read), but there's a key difference in how data is stored. Keeping a set makes little
// sense, as it will only ever hold two tokens, so we can just store those two directly.
//
// The gas savings associated with using these Pools come from how token balances are stored: cash amounts for token
// A and token B are packed together, as are managed amounts. Because only cash changes in a swap, there's no need
// to write to this second storage slot. A single last change block number for both tokens is stored with the packed
// cash fields.
struct TwoTokenPoolBalances {
bytes32 sharedCash;
bytes32 sharedManaged;
}
// We could just keep a mapping from Pool ID to TwoTokenSharedBalances, but there's an issue: we wouldn't know to
// which tokens those balances correspond. This would mean having to also check which are registered with the Pool.
//
// What we do instead to save those storage reads is keep a nested mapping from the token pair hash to the balances
// struct. The Pool only has two tokens, so only a single entry of this mapping is set (the one that corresponds to
// that pair's hash).
//
// This has the trade-off of making Vault code that interacts with these Pools cumbersome: both balances must be
// accessed at the same time by using both token addresses, and some logic is needed to determine how the pair hash
// is computed. We do this by sorting the tokens, calling the token with the lowest numerical address value token A,
// and the other one token B. In functions where the token arguments could be either A or B, we use X and Y instead.
//
// If users query a token pair containing an unregistered token, the Pool will generate a hash for a mapping entry
// that was not set, and return zero balances. Non-zero balances are only possible if both tokens in the pair
// are registered with the Pool, which means we don't have to check the TwoTokenPoolTokens struct, and can save
// storage reads.
struct TwoTokenPoolTokens {
IERC20 tokenA;
IERC20 tokenB;
mapping(bytes32 => TwoTokenPoolBalances) balances;
}
mapping(bytes32 => TwoTokenPoolTokens) private _twoTokenPoolTokens;
/**
* @dev Registers tokens in a Two Token Pool.
*
* This function assumes `poolId` exists and corresponds to the Two Token specialization setting.
*
* Requirements:
*
* - `tokenX` and `tokenY` must not be the same
* - The tokens must be ordered: tokenX < tokenY
*/
function _registerTwoTokenPoolTokens(
bytes32 poolId,
IERC20 tokenX,
IERC20 tokenY
) internal {
// Not technically true since we didn't register yet, but this is consistent with the error messages of other
// specialization settings.
_require(tokenX != tokenY, Errors.TOKEN_ALREADY_REGISTERED);
_require(tokenX < tokenY, Errors.UNSORTED_TOKENS);
// A Two Token Pool with no registered tokens is identified by having zero addresses for tokens A and B.
TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId];
_require(poolTokens.tokenA == IERC20(0) && poolTokens.tokenB == IERC20(0), Errors.TOKENS_ALREADY_SET);
// Since tokenX < tokenY, tokenX is A and tokenY is B
poolTokens.tokenA = tokenX;
poolTokens.tokenB = tokenY;
// Note that we don't initialize the balance mapping: the default value of zero corresponds to an empty
// balance.
}
/**
* @dev Deregisters tokens in a Two Token Pool.
*
* This function assumes `poolId` exists and corresponds to the Two Token specialization setting.
*
* Requirements:
*
* - `tokenX` and `tokenY` must be registered in the Pool
* - both tokens must have zero balance in the Vault
*/
function _deregisterTwoTokenPoolTokens(
bytes32 poolId,
IERC20 tokenX,
IERC20 tokenY
) internal {
(
bytes32 balanceA,
bytes32 balanceB,
TwoTokenPoolBalances storage poolBalances
) = _getTwoTokenPoolSharedBalances(poolId, tokenX, tokenY);
_require(balanceA.isZero() && balanceB.isZero(), Errors.NONZERO_TOKEN_BALANCE);
delete _twoTokenPoolTokens[poolId];
// For consistency with other Pool specialization settings, we explicitly reset the packed cash field (which may
// have a non-zero last change block).
delete poolBalances.sharedCash;
}
/**
* @dev Sets the cash balances of a Two Token Pool's tokens.
*
* WARNING: this assumes `tokenA` and `tokenB` are the Pool's two registered tokens, and are in the correct order.
*/
function _setTwoTokenPoolCashBalances(
bytes32 poolId,
IERC20 tokenA,
bytes32 balanceA,
IERC20 tokenB,
bytes32 balanceB
) internal {
bytes32 pairHash = _getTwoTokenPairHash(tokenA, tokenB);
TwoTokenPoolBalances storage poolBalances = _twoTokenPoolTokens[poolId].balances[pairHash];
poolBalances.sharedCash = BalanceAllocation.toSharedCash(balanceA, balanceB);
}
/**
* @dev Transforms `amount` of `token`'s balance in a Two Token Pool from cash into managed.
*
* This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is
* registered for that Pool.
*/
function _twoTokenPoolCashToManaged(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateTwoTokenPoolSharedBalance(poolId, token, BalanceAllocation.cashToManaged, amount);
}
/**
* @dev Transforms `amount` of `token`'s balance in a Two Token Pool from managed into cash.
*
* This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is
* registered for that Pool.
*/
function _twoTokenPoolManagedToCash(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateTwoTokenPoolSharedBalance(poolId, token, BalanceAllocation.managedToCash, amount);
}
/**
* @dev Sets `token`'s managed balance in a Two Token Pool to `amount`.
*
* This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is
* registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _setTwoTokenPoolManagedBalance(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal returns (int256) {
return _updateTwoTokenPoolSharedBalance(poolId, token, BalanceAllocation.setManaged, amount);
}
/**
* @dev Sets `token`'s balance in a Two Token Pool to the result of the `mutation` function when called with
* the current balance and `amount`.
*
* This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is
* registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _updateTwoTokenPoolSharedBalance(
bytes32 poolId,
IERC20 token,
function(bytes32, uint256) returns (bytes32) mutation,
uint256 amount
) private returns (int256) {
(
TwoTokenPoolBalances storage balances,
IERC20 tokenA,
bytes32 balanceA,
,
bytes32 balanceB
) = _getTwoTokenPoolBalances(poolId);
int256 delta;
if (token == tokenA) {
bytes32 newBalance = mutation(balanceA, amount);
delta = newBalance.managedDelta(balanceA);
balanceA = newBalance;
} else {
// token == tokenB
bytes32 newBalance = mutation(balanceB, amount);
delta = newBalance.managedDelta(balanceB);
balanceB = newBalance;
}
balances.sharedCash = BalanceAllocation.toSharedCash(balanceA, balanceB);
balances.sharedManaged = BalanceAllocation.toSharedManaged(balanceA, balanceB);
return delta;
}
/*
* @dev Returns an array with all the tokens and balances in a Two Token Pool. The order may change when
* tokens are registered or deregistered.
*
* This function assumes `poolId` exists and corresponds to the Two Token specialization setting.
*/
function _getTwoTokenPoolTokens(bytes32 poolId)
internal
view
returns (IERC20[] memory tokens, bytes32[] memory balances)
{
(, IERC20 tokenA, bytes32 balanceA, IERC20 tokenB, bytes32 balanceB) = _getTwoTokenPoolBalances(poolId);
// Both tokens will either be zero (if unregistered) or non-zero (if registered), but we keep the full check for
// clarity.
if (tokenA == IERC20(0) || tokenB == IERC20(0)) {
return (new IERC20[](0), new bytes32[](0));
}
// Note that functions relying on this getter expect tokens to be properly ordered, so we use the (A, B)
// ordering.
tokens = new IERC20[](2);
tokens[0] = tokenA;
tokens[1] = tokenB;
balances = new bytes32[](2);
balances[0] = balanceA;
balances[1] = balanceB;
}
/**
* @dev Same as `_getTwoTokenPoolTokens`, except it returns the two tokens and balances directly instead of using
* an array, as well as a storage pointer to the `TwoTokenPoolBalances` struct, which can be used to update it
* without having to recompute the pair hash and storage slot.
*/
function _getTwoTokenPoolBalances(bytes32 poolId)
private
view
returns (
TwoTokenPoolBalances storage poolBalances,
IERC20 tokenA,
bytes32 balanceA,
IERC20 tokenB,
bytes32 balanceB
)
{
TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId];
tokenA = poolTokens.tokenA;
tokenB = poolTokens.tokenB;
bytes32 pairHash = _getTwoTokenPairHash(tokenA, tokenB);
poolBalances = poolTokens.balances[pairHash];
bytes32 sharedCash = poolBalances.sharedCash;
bytes32 sharedManaged = poolBalances.sharedManaged;
balanceA = BalanceAllocation.fromSharedToBalanceA(sharedCash, sharedManaged);
balanceB = BalanceAllocation.fromSharedToBalanceB(sharedCash, sharedManaged);
}
/**
* @dev Returns the balance of a token in a Two Token Pool.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*
* This function is convenient but not particularly gas efficient, and should be avoided during gas-sensitive
* operations, such as swaps. For those, _getTwoTokenPoolSharedBalances provides a more flexible interface.
*
* Requirements:
*
* - `token` must be registered in the Pool
*/
function _getTwoTokenPoolBalance(bytes32 poolId, IERC20 token) internal view returns (bytes32) {
// We can't just read the balance of token, because we need to know the full pair in order to compute the pair
// hash and access the balance mapping. We therefore rely on `_getTwoTokenPoolBalances`.
(, IERC20 tokenA, bytes32 balanceA, IERC20 tokenB, bytes32 balanceB) = _getTwoTokenPoolBalances(poolId);
if (token == tokenA) {
return balanceA;
} else if (token == tokenB) {
return balanceB;
} else {
_revert(Errors.TOKEN_NOT_REGISTERED);
}
}
/**
* @dev Returns the balance of the two tokens in a Two Token Pool.
*
* The returned balances are those of token A and token B, where token A is the lowest of token X and token Y, and
* token B the other.
*
* This function also returns a storage pointer to the TwoTokenPoolBalances struct associated with the token pair,
* which can be used to update it without having to recompute the pair hash and storage slot.
*
* Requirements:
*
* - `poolId` must be a Minimal Swap Info Pool
* - `tokenX` and `tokenY` must be registered in the Pool
*/
function _getTwoTokenPoolSharedBalances(
bytes32 poolId,
IERC20 tokenX,
IERC20 tokenY
)
internal
view
returns (
bytes32 balanceA,
bytes32 balanceB,
TwoTokenPoolBalances storage poolBalances
)
{
(IERC20 tokenA, IERC20 tokenB) = _sortTwoTokens(tokenX, tokenY);
bytes32 pairHash = _getTwoTokenPairHash(tokenA, tokenB);
poolBalances = _twoTokenPoolTokens[poolId].balances[pairHash];
// Because we're reading balances using the pair hash, if either token X or token Y is not registered then
// *both* balance entries will be zero.
bytes32 sharedCash = poolBalances.sharedCash;
bytes32 sharedManaged = poolBalances.sharedManaged;
// A non-zero balance guarantees that both tokens are registered. If zero, we manually check whether each
// token is registered in the Pool. Token registration implies that the Pool is registered as well, which
// lets us save gas by not performing the check.
bool tokensRegistered = sharedCash.isNotZero() ||
sharedManaged.isNotZero() ||
(_isTwoTokenPoolTokenRegistered(poolId, tokenA) && _isTwoTokenPoolTokenRegistered(poolId, tokenB));
if (!tokensRegistered) {
// The tokens might not be registered because the Pool itself is not registered. We check this to provide a
// more accurate revert reason.
_ensureRegisteredPool(poolId);
_revert(Errors.TOKEN_NOT_REGISTERED);
}
balanceA = BalanceAllocation.fromSharedToBalanceA(sharedCash, sharedManaged);
balanceB = BalanceAllocation.fromSharedToBalanceB(sharedCash, sharedManaged);
}
/**
* @dev Returns true if `token` is registered in a Two Token Pool.
*
* This function assumes `poolId` exists and corresponds to the Two Token specialization setting.
*/
function _isTwoTokenPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) {
TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId];
// The zero address can never be a registered token.
return (token == poolTokens.tokenA || token == poolTokens.tokenB) && token != IERC20(0);
}
/**
* @dev Returns the hash associated with a given token pair.
*/
function _getTwoTokenPairHash(IERC20 tokenA, IERC20 tokenB) private pure returns (bytes32) {
return keccak256(abi.encodePacked(tokenA, tokenB));
}
/**
* @dev Sorts two tokens in ascending order, returning them as a (tokenA, tokenB) tuple.
*/
function _sortTwoTokens(IERC20 tokenX, IERC20 tokenY) private pure returns (IERC20, IERC20) {
return tokenX < tokenY ? (tokenX, tokenY) : (tokenY, tokenX);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/math/Math.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/helpers/AssetHelpers.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "../lib/openzeppelin/Address.sol";
import "./interfaces/IWETH.sol";
import "./interfaces/IAsset.sol";
import "./interfaces/IVault.sol";
abstract contract AssetTransfersHandler is AssetHelpers {
using SafeERC20 for IERC20;
using Address for address payable;
/**
* @dev Receives `amount` of `asset` from `sender`. If `fromInternalBalance` is true, it first withdraws as much
* as possible from Internal Balance, then transfers any remaining amount.
*
* If `asset` is ETH, `fromInternalBalance` must be false (as ETH cannot be held as internal balance), and the funds
* will be wrapped into WETH.
*
* WARNING: this function does not check that the contract caller has actually supplied any ETH - it is up to the
* caller of this function to check that this is true to prevent the Vault from using its own ETH (though the Vault
* typically doesn't hold any).
*/
function _receiveAsset(
IAsset asset,
uint256 amount,
address sender,
bool fromInternalBalance
) internal {
if (amount == 0) {
return;
}
if (_isETH(asset)) {
_require(!fromInternalBalance, Errors.INVALID_ETH_INTERNAL_BALANCE);
// The ETH amount to receive is deposited into the WETH contract, which will in turn mint WETH for
// the Vault at a 1:1 ratio.
// A check for this condition is also introduced by the compiler, but this one provides a revert reason.
// Note we're checking for the Vault's total balance, *not* ETH sent in this transaction.
_require(address(this).balance >= amount, Errors.INSUFFICIENT_ETH);
_WETH().deposit{ value: amount }();
} else {
IERC20 token = _asIERC20(asset);
if (fromInternalBalance) {
// We take as many tokens from Internal Balance as possible: any remaining amounts will be transferred.
uint256 deductedBalance = _decreaseInternalBalance(sender, token, amount, true);
// Because `deductedBalance` will be always the lesser of the current internal balance
// and the amount to decrease, it is safe to perform unchecked arithmetic.
amount -= deductedBalance;
}
if (amount > 0) {
token.safeTransferFrom(sender, address(this), amount);
}
}
}
/**
* @dev Sends `amount` of `asset` to `recipient`. If `toInternalBalance` is true, the asset is deposited as Internal
* Balance instead of being transferred.
*
* If `asset` is ETH, `toInternalBalance` must be false (as ETH cannot be held as internal balance), and the funds
* are instead sent directly after unwrapping WETH.
*/
function _sendAsset(
IAsset asset,
uint256 amount,
address payable recipient,
bool toInternalBalance
) internal {
if (amount == 0) {
return;
}
if (_isETH(asset)) {
// Sending ETH is not as involved as receiving it: the only special behavior is it cannot be
// deposited to Internal Balance.
_require(!toInternalBalance, Errors.INVALID_ETH_INTERNAL_BALANCE);
// First, the Vault withdraws deposited ETH from the WETH contract, by burning the same amount of WETH
// from the Vault. This receipt will be handled by the Vault's `receive`.
_WETH().withdraw(amount);
// Then, the withdrawn ETH is sent to the recipient.
recipient.sendValue(amount);
} else {
IERC20 token = _asIERC20(asset);
if (toInternalBalance) {
_increaseInternalBalance(recipient, token, amount);
} else {
token.safeTransfer(recipient, amount);
}
}
}
/**
* @dev Returns excess ETH back to the contract caller, assuming `amountUsed` has been spent. Reverts
* if the caller sent less ETH than `amountUsed`.
*
* Because the caller might not know exactly how much ETH a Vault action will require, they may send extra.
* Note that this excess value is returned *to the contract caller* (msg.sender). If caller and e.g. swap sender are
* not the same (because the caller is a relayer for the sender), then it is up to the caller to manage this
* returned ETH.
*/
function _handleRemainingEth(uint256 amountUsed) internal {
_require(msg.value >= amountUsed, Errors.INSUFFICIENT_ETH);
uint256 excess = msg.value - amountUsed;
if (excess > 0) {
msg.sender.sendValue(excess);
}
}
/**
* @dev Enables the Vault to receive ETH. This is required for it to be able to unwrap WETH, which sends ETH to the
* caller.
*
* Any ETH sent to the Vault outside of the WETH unwrapping mechanism would be forever locked inside the Vault, so
* we prevent that from happening. Other mechanisms used to send ETH to the Vault (such as being the recipient of an
* ETH swap, Pool exit or withdrawal, contract self-destruction, or receiving the block mining reward) will result
* in locked funds, but are not otherwise a security or soundness issue. This check only exists as an attempt to
* prevent user error.
*/
receive() external payable {
_require(msg.sender == address(_WETH()), Errors.ETH_TRANSFER);
}
// This contract uses virtual internal functions instead of inheriting from the modules that implement them (in
// this case UserBalance) in order to decouple it from the rest of the system and enable standalone testing by
// implementing these with mocks.
function _increaseInternalBalance(
address account,
IERC20 token,
uint256 amount
) internal virtual;
function _decreaseInternalBalance(
address account,
IERC20 token,
uint256 amount,
bool capped
) internal virtual returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../openzeppelin/IERC20.sol";
import "../../vault/interfaces/IAsset.sol";
import "../../vault/interfaces/IWETH.sol";
abstract contract AssetHelpers {
// solhint-disable-next-line var-name-mixedcase
IWETH private immutable _weth;
// Sentinel value used to indicate WETH with wrapping/unwrapping semantics. The zero address is a good choice for
// multiple reasons: it is cheap to pass as a calldata argument, it is a known invalid token and non-contract, and
// it is an address Pools cannot register as a token.
address private constant _ETH = address(0);
constructor(IWETH weth) {
_weth = weth;
}
// solhint-disable-next-line func-name-mixedcase
function _WETH() internal view returns (IWETH) {
return _weth;
}
/**
* @dev Returns true if `asset` is the sentinel value that represents ETH.
*/
function _isETH(IAsset asset) internal pure returns (bool) {
return address(asset) == _ETH;
}
/**
* @dev Translates `asset` into an equivalent IERC20 token address. If `asset` represents ETH, it will be translated
* to the WETH contract.
*/
function _translateToIERC20(IAsset asset) internal view returns (IERC20) {
return _isETH(asset) ? _WETH() : _asIERC20(asset);
}
/**
* @dev Same as `_translateToIERC20(IAsset)`, but for an entire array.
*/
function _translateToIERC20(IAsset[] memory assets) internal view returns (IERC20[] memory) {
IERC20[] memory tokens = new IERC20[](assets.length);
for (uint256 i = 0; i < assets.length; ++i) {
tokens[i] = _translateToIERC20(assets[i]);
}
return tokens;
}
/**
* @dev Interprets `asset` as an IERC20 token. This function should only be called on `asset` if `_isETH` previously
* returned false for it, that is, if `asset` is guaranteed not to be the ETH sentinel value.
*/
function _asIERC20(IAsset asset) internal pure returns (IERC20) {
return IERC20(address(asset));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @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, Errors.ADDRESS_INSUFFICIENT_BALANCE);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
_require(success, Errors.ADDRESS_CANNOT_SEND_VALUE);
}
}
| Sets `account`'s Internal Balance for `token` to `newBalance`. Emits an `InternalBalanceChanged` event. This event includes `delta`, which is the amount the balance increased (if positive) or decreased (if negative). To avoid reading the current balance in order to compute the delta, this function relies on the caller providing it directly./ | function _setInternalBalance(
address account,
IERC20 token,
uint256 newBalance,
int256 delta
) private {
_internalTokenBalance[account][token] = newBalance;
emit InternalBalanceChanged(account, token, delta);
}
| 642,233 |
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/utils/Strings.sol
// 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/Address.sol
// 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/token/ERC721/IERC721Receiver.sol
// 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);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// 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/ERC165.sol
// 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/token/ERC721/IERC721.sol
// 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/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @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);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @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);
}
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol
// 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;
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// 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: contracts/ERC721A.sol
// Creator: Chiru Labs
pragma solidity ^0.8.0;
/**
* @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..).
*
* Does not support burning tokens to address(0).
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex = 0;
uint256 internal immutable maxBatchSize;
// 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) private _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;
/**
* @dev
* `maxBatchSize` refers to how much a minter can mint at a time.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_
) {
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @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) {
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @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) {
require(owner != address(0), "ERC721A: balance query for the zero address");
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(owner != address(0), "ERC721A: number minted query for the zero address");
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @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) {
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 override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721A: 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 override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: 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`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = 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 ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved");
require(prevOwnership.addr == from, "ERC721A: transfer from incorrect owner");
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, 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)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(prevOwnership.addr, prevOwnership.startTimestamp);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @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);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > currentIndex - 1) {
endIndex = currentIndex - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(ownership.addr, ownership.startTimestamp);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @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("ERC721A: transfer to non ERC721Receiver implementer");
} 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.
*
* 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`.
*/
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.
*
* 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` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
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.
*
* 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);
}
}
// File: contracts/DAPE.sol
pragma solidity ^0.8.0;
contract DAPE is Ownable, ERC721A, ReentrancyGuard {
string public uriPrefix = "";
string public constant uriSuffix = ".json";
string public hiddenMetadataUri;
uint256 public collectionSize = 8888;
uint256 public auctionStartPrice;
uint256 public maxPerAddressDuringMint = 4;
bool public revealed = false;
// number of items to include in auction and for giveaways
uint256 public amountForAuctionAndDev = 6655;
// used for giveaways
uint256 public amountForDevs = 144;
struct SaleConfig {
uint32 allowListSaleStartTime;
uint32 auctionSaleStartTime;
uint32 publicSaleStartTime;
uint64 mintlistPrice;
uint64 publicPrice;
}
SaleConfig public saleConfig;
mapping(address => uint256) public allowlist;
// Name, Symbol, Max batch size, collection size.
constructor() ERC721A("DAPE", "DAPE", maxPerAddressDuringMint) {
require(
amountForAuctionAndDev <= collectionSize,
"larger collection size needed"
);
require (
amountForDevs % maxPerAddressDuringMint == 0,
"dev mints must be multiple of maxbatchsize"
);
setHiddenMetadataUri("ipfs://__CID__/hidden.json");
}
modifier callerIsUser() {
require(tx.origin == msg.sender, "The caller is another contract");
_;
}
// REGION - Mint functions and helpers
function auctionMint(uint256 quantity) external payable callerIsUser {
uint256 _saleStartTime = uint256(saleConfig.auctionSaleStartTime);
require(
_saleStartTime != 0 && block.timestamp >= _saleStartTime,
"auction sale has not started yet"
);
require(
totalSupply() + quantity <= amountForAuctionAndDev,
"not enough remaining reserved for auction to support desired mint amount"
);
require(
numberMinted(msg.sender) + quantity <= maxPerAddressDuringMint,
"can not mint this many"
);
uint256 totalCost = getAuctionPrice(_saleStartTime) * quantity;
refundIfOver(totalCost);
_safeMint(msg.sender, quantity);
}
function publicSaleMint(uint256 quantity)
external
payable
callerIsUser
{
SaleConfig memory config = saleConfig;
uint256 publicPrice = uint256(config.publicPrice);
uint256 publicSaleStartTime = uint256(config.publicSaleStartTime);
require(
isPublicSaleOn(publicPrice, publicSaleStartTime),
"public sale has not begun yet"
);
require(totalSupply() + quantity <= collectionSize, "reached max supply");
require(
numberMinted(msg.sender) + quantity <= maxPerAddressDuringMint,
"can not mint this many"
);
refundIfOver(publicPrice * quantity);
_safeMint(msg.sender, quantity);
}
function allowlistMint() external payable callerIsUser {
uint256 _allowListStartTime = uint256(saleConfig.allowListSaleStartTime);
require(
_allowListStartTime != 0 && block.timestamp >= _allowListStartTime,
"white list sale has not begun yet or has ended"
);
uint256 price = uint256(saleConfig.mintlistPrice);
require(price != 0, "white list sale has not begun yet or has ended");
require(allowlist[msg.sender] > 0, "not eligible for white list mint");
require(totalSupply() + 1 <= collectionSize, "reached max supply");
if (allowlist[msg.sender] == 1) {
delete allowlist[msg.sender];
} else {
allowlist[msg.sender]--;
}
refundIfOver(price);
_safeMint(msg.sender, 1);
}
function refundIfOver(uint256 price) private {
require(msg.value >= price, "Need to send more ETH.");
if (msg.value > price) {
payable(msg.sender).transfer(msg.value - price);
}
}
function isPublicSaleOn(
uint256 publicPriceWei,
uint256 publicSaleStartTime
) public view returns (bool) {
return
publicPriceWei != 0 &&
block.timestamp >= publicSaleStartTime;
}
function isAllowListSaleOn()
public view returns (bool) {
uint256 _allowListStartTime = uint256(saleConfig.allowListSaleStartTime);
return _allowListStartTime != 0 && block.timestamp >= _allowListStartTime;
}
// Mint for marketing and giveaways
function devMint(uint256 quantity) external onlyOwner {
require(
totalSupply() + quantity <= amountForDevs,
"too many already minted before dev mint"
);
require(
quantity % maxBatchSize == 0,
"can only mint a multiple of the maxBatchSize"
);
uint256 numChunks = quantity / maxBatchSize;
for (uint256 i = 0; i < numChunks; i++) {
_safeMint(msg.sender, maxBatchSize);
}
}
uint256 public constant AUCTION_END_PRICE = 0.3 ether;
uint256 public constant AUCTION_DROP_INTERVAL = 10 minutes;
uint256 public constant AUCTION_DROP_PER_STEP = 0.05 ether;
function getAuctionPrice(uint256 _saleStartTime)
public
view
returns (uint256)
{
if (block.timestamp < _saleStartTime) {
return auctionStartPrice;
}
uint256 auctionCurveLength = getAuctionCurveLength();
if (block.timestamp - _saleStartTime >= auctionCurveLength) {
return AUCTION_END_PRICE;
} else {
uint256 steps = (block.timestamp - _saleStartTime) /
AUCTION_DROP_INTERVAL;
return auctionStartPrice - (steps * AUCTION_DROP_PER_STEP);
}
}
function endAuctionAndSetupNonAuctionSaleInfo(
uint64 mintlistPriceWei,
uint64 publicPriceWei,
uint32 publicSaleStartTime
) external onlyOwner {
saleConfig = SaleConfig(
0, //allow list sale start time
0, //auction sale start time
publicSaleStartTime,
mintlistPriceWei,
publicPriceWei
);
}
function getAuctionCurveLength(
) public view returns (uint256) {
return
((auctionStartPrice - AUCTION_END_PRICE) * AUCTION_DROP_INTERVAL) /
AUCTION_DROP_PER_STEP;
}
function setAuctionStartPrice(
uint256 startPriceWei
) external onlyOwner {
auctionStartPrice = startPriceWei;
}
function setMintListPrice(
uint64 mintListPriceWei
) external onlyOwner {
saleConfig.mintlistPrice = mintListPriceWei;
}
function setAllowListSaleStartTime(uint32 timestamp) external onlyOwner {
saleConfig.allowListSaleStartTime = timestamp;
}
function setAuctionSaleStartTime(uint32 timestamp) external onlyOwner {
saleConfig.auctionSaleStartTime = timestamp;
}
function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner {
hiddenMetadataUri = _hiddenMetadataUri;
}
function seedAllowlist(address[] memory addresses, uint256[] memory numSlots)
external
onlyOwner
{
require(
addresses.length == numSlots.length,
"addresses does not match numSlots length"
);
for (uint256 i = 0; i < addresses.length; i++) {
allowlist[addresses[i]] = numSlots[i];
}
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721AMetadata: URI query for nonexistant token"
);
if(revealed == false) {
return hiddenMetadataUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, Strings.toString(tokenId), uriSuffix))
: "";
}
// metadata URI
string private _baseTokenURI;
function reveal() public onlyOwner {
revealed = true;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string calldata baseURI) external onlyOwner {
_baseTokenURI = baseURI;
}
function withdrawMoney() external onlyOwner nonReentrant {
(bool success, ) = msg.sender.call{value: address(this).balance}("");
require(success, "Transfer failed.");
}
function setOwnersExplicit(uint256 quantity) external onlyOwner nonReentrant {
_setOwnersExplicit(quantity);
}
function numberMinted(address owner) public view returns (uint256) {
return _numberMinted(owner);
}
function getOwnershipData(uint256 tokenId)
external
view
returns (TokenOwnership memory)
{
return ownershipOf(tokenId);
}
} | Explicitly set `owners` to eliminate loops in future calls of ownerOf()./ | function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > currentIndex - 1) {
endIndex = currentIndex - 1;
}
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(ownership.addr, ownership.startTimestamp);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
| 150,289 |
./partial_match/3/0x735110791D1DD21032c310F0DbFE167d54F84A64/sources/FarmUniswap.sol | withdraw LP token function for msgSender _amount the total withdrawable amount/ | function withdraw(uint256 _amount) public {
address msgSender = _msgSender();
UserInfo storage user = userInfo[msgSender];
require(user.amount >= _amount, "INSUFFICIENT");
updatePool();
if (user.amount == _amount && _amount > 0) {
factory.userLeftFarm(msgSender);
farmInfo.numFarmers = farmInfo.numFarmers.sub(1);
}
uint256 pending = user.amount.mul(farmInfo.accRewardPerShare).div(1e12).sub(user.rewardDebt);
safeRewardTransfer(msgSender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(farmInfo.accRewardPerShare).div(1e12);
farmInfo.lpToken.safeTransfer(address(msgSender), _amount);
emit Withdraw(msgSender, _amount);
}
| 5,136,452 |
./partial_match/3/0x25E2e5D8EcC4fE46a9505079Ed29266779dC7D6f/sources/HoprChannels.sol | Fund a channel between 'accountA' and 'accountB', specified tokens must be approved beforehand. Called when HOPR tokens are send to this contract. fund a channel additionalDeposit uint256 amount to fund the channel funder address account which the funds are for recipient address account of first participant of the payment channel counterparty address account of the second participant of the payment channel/ The state counter indicates the recycling generation and ensures that both parties are using the correct generation. | function fundChannel(
uint256 additionalDeposit,
address funder,
address recipient,
address counterparty
) internal {
require(recipient != counterparty, "HoprChannels: 'recipient' and 'counterParty' must not be the same");
require(recipient != address(0), "HoprChannels: 'recipient' address is empty");
require(counterparty != address(0), "HoprChannels: 'counterParty' address is empty");
require(additionalDeposit > 0, "HoprChannels: 'additionalDeposit' must be greater than 0");
require(additionalDeposit < (1 << 96), "HoprChannels: preventing 'amount' overflow");
require(accounts[recipient].accountX != uint256(0), "HoprChannels: initiator must have called init() before");
require(
accounts[counterparty].accountX != uint256(0),
"HoprChannels: counterparty must have called init() before"
);
(address partyA, , Channel storage channel, ChannelStatus status) = getChannel(recipient, counterparty);
require(
status == ChannelStatus.UNINITIALISED || status == ChannelStatus.FUNDED,
"HoprChannels: channel must be 'UNINITIALISED' or 'FUNDED'"
);
require(
recipient != partyA || channel.partyABalance + additionalDeposit < (1 << 96),
"HoprChannels: Invalid amount"
);
require(channel.deposit + additionalDeposit < (1 << 96), "HoprChannels: Invalid amount");
require(channel.stateCounter + 1 < (1 << 24), "HoprChannels: Preventing stateCounter overflow");
channel.deposit += uint96(additionalDeposit);
if (recipient == partyA) {
channel.partyABalance += uint96(additionalDeposit);
}
if (status == ChannelStatus.UNINITIALISED) {
channel.stateCounter += 1;
}
emitFundedChannel(funder, recipient, counterparty, additionalDeposit, 0);
}
| 5,147,871 |
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
import "../libs/SafeMath.sol";
import "../libs/SignedSafeMath.sol";
import {Classifier64} from "./Classifier.sol";
contract Perceptron is Classifier64 {
using SafeMath for uint256;
using SignedSafeMath for int256;
mapping(uint64 => int80) public weights;
int80 public intercept;
uint8 public learningRate;
constructor(
string[] memory _classifications,
int80[] memory _weights,
int80 _intercept,
uint8 _learningRate
) Classifier64(_classifications) public {
require(_learningRate > 0, "The learning rate must be > 0.");
intercept = _intercept;
learningRate = _learningRate;
require(_weights.length < 2**64 - 1, "Too many weights given.");
for (uint64 i = 0; i < _weights.length; ++i) {
weights[i] = _weights[i];
}
}
/**
* Initialize weights for the model.
* Made to be called just after the contract is created and never again.
* @param startIndex The index to start placing `_weights` into the model's weights.
* @param _weights The weights to set for the model.
*/
function initializeWeights(uint64 startIndex, int80[] memory _weights) public onlyOwner {
for (uint64 i = 0; i < _weights.length; ++i) {
weights[startIndex + i] = _weights[i];
}
}
function norm(int64[] memory /* data */) public pure returns (uint) {
revert("Normalization is not required.");
}
function predict(int64[] memory data) public view returns (uint64) {
int m = intercept;
for (uint i = 0; i < data.length; ++i) {
// `update` assumes this check is done.
require(data[i] >= 0, "Not all indices are >= 0.");
m = m.add(weights[uint64(data[i])]);
}
if (m <= 0) {
return 0;
} else {
return 1;
}
}
function update(int64[] memory data, uint64 classification) public onlyOwner {
uint64 prediction = predict(data);
if (prediction != classification) {
// Update model.
// predict checks each data[i] >= 0.
uint i;
uint len = data.length;
// Data is binarized.
int80 change = toFloat * learningRate;
if (classification > 0) {
// sign = 1
for(i = 0; i < len; ++i) {
weights[uint64(data[i])] += change;
}
} else {
// sign = -1
for(i = 0; i < len; ++i) {
weights[uint64(data[i])] -= change;
}
}
}
}
/**
* Evaluate a batch.
*
* Force samples to have a size of 60 because about 78% of the IMDB test data has less than 60 tokens. If the sample has less than 60 unique tokens, then use a value > weights.length.
*
* @return The number correct in the batch.
*/
function evaluateBatch(uint24[60][] calldata dataBatch, uint64[] calldata _classifications) external view returns (uint numCorrect) {
numCorrect = 0;
uint len = dataBatch.length;
uint i;
uint dataLen;
uint24[60] memory data;
int80 prediction;
for (uint dataIndex = 0; dataIndex < len; ++dataIndex) {
data = dataBatch[dataIndex];
// Re-implement prediction for speed and to handle the type of data not matching.
prediction = intercept;
dataLen = data.length;
for (i = 0; i < dataLen; ++i) {
prediction += weights[data[i]];
}
if (prediction <= 0) {
prediction = 0;
} else {
prediction = 1;
}
if (prediction == _classifications[dataIndex]) {
numCorrect += 1;
}
}
}
}
| Update model. predict checks each data[i] >= 0. Data is binarized. sign = 1 sign = -1 | function update(int64[] memory data, uint64 classification) public onlyOwner {
uint64 prediction = predict(data);
if (prediction != classification) {
uint i;
uint len = data.length;
int80 change = toFloat * learningRate;
if (classification > 0) {
for(i = 0; i < len; ++i) {
weights[uint64(data[i])] += change;
}
for(i = 0; i < len; ++i) {
weights[uint64(data[i])] -= change;
}
}
}
}
| 5,395,265 |
./partial_match/1/0xd81b3000D6Cad7af85E9939AfAb1243B56618EA9/sources/VFIN.sol | Token migration / Migrate contract. ===> CAUTION: DEFINITIVE ACTION This function shall be called once a new version of the smart contract has been created. Once this function is called: - The address of the new smart contract is set in ERC1820 registry - If the choice is definitive, the current smart contract is turned off and can never be used again newContractAddress Address of the new version of the smart contract. definitive If set to 'true' the contract is turned off definitely./ | function _migrate(address newContractAddress, bool definitive) internal {
ERC1820Client.setInterfaceImplementation(ERC20_INTERFACE_NAME, newContractAddress);
ERC1820Client.setInterfaceImplementation(ERC1400_INTERFACE_NAME, newContractAddress);
if(definitive) {
_migrated = true;
}
}
| 4,032,173 |
./partial_match/1/0x85cdDcE5C1889D84e10d97074b7Af007f2CaDCC5/sources/BankrollNetworkStackPlus.sol | Retrieve the dividends owned by the caller./ | function myDividends() public view returns (uint256) {
address _customerAddress = msg.sender;
return dividendsOf(_customerAddress);
}
| 11,023,174 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
library Math {
/// Cannot Declare State var (it's not a contract, just helper function)
function max(uint256 x, uint256 y) internal pure returns (uint256) {
return x >= y ? x : y;
}
function min(uint256 x, uint256 y) internal pure returns (uint256) {
return x <= y ? x : y;
}
function add(uint256 x, uint256 y) internal pure returns (uint256) {
return x + y;
}
function sub(uint256 x, uint256 y) internal pure returns (uint256) {
return x - y;
}
function mul(uint256 x, uint256 y) internal pure returns (uint256) {
return x * y;
}
function div(uint256 x, uint256 y) internal pure returns (uint256) {
return x / y;
}
}
library ArrayLib {
function find(uint256[] storage arr, uint256 x)
internal
view
returns (uint256)
{
for (uint256 i = 0; i < arr.length; i++) {
if (arr[i] == x) {
return i;
}
}
revert("not found");
}
}
contract Test {
using Math for uint256; // Method 2 declaring extra function for a type
function testMax(uint256 x, uint256 y) external pure returns (uint256) {
return Math.max(x, y); // Method 1: Direct call
}
function testMin(uint256 x, uint256 y) external pure returns (uint256) {
return x.min(y); /// Method 2 Application
}
}
contract TestArray {
using ArrayLib for uint256[]; // Method 2
uint256[] public arr = [3, 2, 1];
function testFind() external view returns (uint256 i) {
// return ArrayLib.find(arr, 2);
return arr.find(2);
}
}
| Cannot Declare State var (it's not a contract, just helper function) | function max(uint256 x, uint256 y) internal pure returns (uint256) {
return x >= y ? x : y;
}
| 12,911,788 |
/**
* MPSBoardSig.sol
* Governance smart contract including multi-signature capabilities.
* It uniquely represents the Board of Directors of Mt Pelerin Group SA on-chain
* until it is superseded by a resolution of the board referring to a new
* governance on-chain reference.
* The unflattened code is available through this github tag:
* https://github.com/MtPelerin/MtPelerin-protocol/tree/etherscan-verify-batch-1
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice All matters regarding the intellectual property of this code
* @notice or software are subject to Swiss Law without reference to its
* @notice conflicts of law rules.
* @notice License for each contract is available in the respective file
* @notice or in the LICENSE.md file.
* @notice https://github.com/MtPelerin/
* @notice Code by OpenZeppelin is copyrighted and licensed on their repository:
* @notice https://github.com/OpenZeppelin/openzeppelin-solidity
*/
pragma solidity ^0.4.24;
// File: contracts/multisig/private/MultiSig.sol
/**
* @title MultiSig
* @dev MultiSig contract
* @author Cyril Lapinte - <[email protected]>
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
* Error messages
* MS01: Valid signatures below threshold
* MS02: Transaction validity has expired
* MS03: Sender does not belong to signers
* MS04: Execution should be correct
*/
contract MultiSig {
address[] signers_;
uint8 public threshold;
bytes32 public replayProtection;
uint256 public nonce;
/**
* @dev constructor
*/
constructor(address[] _signers, uint8 _threshold) public {
signers_ = _signers;
threshold = _threshold;
// Prevent first transaction of different contracts
// to be replayed here
updateReplayProtection();
}
/**
* @dev fallback function
*/
function () public payable { }
/**
* @dev read a function selector from a bytes field
* @param _data contains the selector
*/
function readSelector(bytes _data) public pure returns (bytes4) {
bytes4 selector;
// solium-disable-next-line security/no-inline-assembly
assembly {
selector := mload(add(_data, 0x20))
}
return selector;
}
/**
* @dev read ERC20 destination
* @param _data ERC20 transfert
*/
function readERC20Destination(bytes _data) public pure returns (address) {
address destination;
// solium-disable-next-line security/no-inline-assembly
assembly {
destination := mload(add(_data, 0x24))
}
return destination;
}
/**
* @dev read ERC20 value
* @param _data contains the selector
*/
function readERC20Value(bytes _data) public pure returns (uint256) {
uint256 value;
// solium-disable-next-line security/no-inline-assembly
assembly {
value := mload(add(_data, 0x44))
}
return value;
}
/**
* @dev Modifier verifying that valid signatures are above _threshold
*/
modifier thresholdRequired(
address _destination, uint256 _value, bytes _data,
uint256 _validity, uint256 _threshold,
bytes32[] _sigR, bytes32[] _sigS, uint8[] _sigV)
{
require(
reviewSignatures(
_destination, _value, _data, _validity, _sigR, _sigS, _sigV
) >= _threshold,
"MS01"
);
_;
}
/**
* @dev Modifier verifying that transaction is still valid
* @dev This modifier also protects against replay on forked chain.
*
* @notice If both the _validity and gasPrice are low, then there is a risk
* @notice that the transaction is executed after its _validity but before it does timeout
* @notice In that case, the transaction will fail.
* @notice In general, it is recommended to use a _validity greater than the potential timeout
*/
modifier stillValid(uint256 _validity)
{
if (_validity != 0) {
require(_validity >= block.number, "MS02");
}
_;
}
/**
* @dev Modifier requiring that the message sender belongs to the signers
*/
modifier onlySigners() {
bool found = false;
for (uint256 i = 0; i < signers_.length && !found; i++) {
found = (msg.sender == signers_[i]);
}
require(found, "MS03");
_;
}
/**
* @dev returns signers
*/
function signers() public view returns (address[]) {
return signers_;
}
/**
* returns threshold
*/
function threshold() public view returns (uint8) {
return threshold;
}
/**
* @dev returns replayProtection
*/
function replayProtection() public view returns (bytes32) {
return replayProtection;
}
/**
* @dev returns nonce
*/
function nonce() public view returns (uint256) {
return nonce;
}
/**
* @dev returns the number of valid signatures
*/
function reviewSignatures(
address _destination, uint256 _value, bytes _data,
uint256 _validity,
bytes32[] _sigR, bytes32[] _sigS, uint8[] _sigV)
public view returns (uint256)
{
return reviewSignaturesInternal(
_destination,
_value,
_data,
_validity,
signers_,
_sigR,
_sigS,
_sigV
);
}
/**
* @dev buildHash
**/
function buildHash(
address _destination, uint256 _value,
bytes _data, uint256 _validity)
public view returns (bytes32)
{
// FIXME: web3/solidity behaves differently with empty bytes
if (_data.length == 0) {
return keccak256(
abi.encode(
_destination, _value, _validity, replayProtection
)
);
} else {
return keccak256(
abi.encode(
_destination, _value, _data, _validity, replayProtection
)
);
}
}
/**
* @dev recover the public address from the signatures
**/
function recoverAddress(
address _destination, uint256 _value,
bytes _data, uint256 _validity,
bytes32 _r, bytes32 _s, uint8 _v)
public view returns (address)
{
// When used in web.eth.sign, geth will prepend the hash
bytes32 hash = keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32",
buildHash(
_destination,
_value,
_data,
_validity
)
)
);
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
uint8 v = (_v < 27) ? _v += 27: _v;
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return address(0);
} else {
return ecrecover(
hash,
v,
_r,
_s
);
}
}
/**
* @dev execute a transaction if enough signatures are valid
**/
function execute(
bytes32[] _sigR,
bytes32[] _sigS,
uint8[] _sigV,
address _destination, uint256 _value, bytes _data, uint256 _validity)
public
stillValid(_validity)
thresholdRequired(_destination, _value, _data, _validity, threshold, _sigR, _sigS, _sigV)
returns (bool)
{
executeInternal(_destination, _value, _data);
return true;
}
/**
* @dev review signatures against a list of signers
* Signatures must be provided in the same order as the list of signers
* All provided signatures must be valid and correspond to one of the signers
* returns the number of valid signatures
* returns 0 if the inputs are inconsistent
*/
function reviewSignaturesInternal(
address _destination, uint256 _value, bytes _data, uint256 _validity,
address[] _signers,
bytes32[] _sigR, bytes32[] _sigS, uint8[] _sigV)
internal view returns (uint256)
{
uint256 length = _sigR.length;
if (length == 0 || length > _signers.length || (
_sigS.length != length || _sigV.length != length
))
{
return 0;
}
uint256 validSigs = 0;
address recovered = recoverAddress(
_destination, _value, _data, _validity,
_sigR[0], _sigS[0], _sigV[0]);
for (uint256 i = 0; i < _signers.length; i++) {
if (_signers[i] == recovered) {
validSigs++;
if (validSigs < length) {
recovered = recoverAddress(
_destination,
_value,
_data,
_validity,
_sigR[validSigs],
_sigS[validSigs],
_sigV[validSigs]
);
} else {
break;
}
}
}
if (validSigs != length) {
return 0;
}
return validSigs;
}
/**
* @dev execute a transaction
**/
function executeInternal(address _destination, uint256 _value, bytes _data)
internal
{
updateReplayProtection();
if (_data.length == 0) {
_destination.transfer(_value);
} else {
// solium-disable-next-line security/no-call-value
require(_destination.call.value(_value)(_data), "MS04");
}
emit Execution(_destination, _value, _data);
}
/**
* @dev update replay protection
* contract address is used to prevent replay between different contracts
* block hash is used to prevent replay between branches
* nonce is used to prevent replay within the contract
**/
function updateReplayProtection() internal {
replayProtection = keccak256(
abi.encodePacked(address(this), blockhash(block.number-1), nonce));
nonce++;
}
event Execution(address to, uint256 value, bytes data);
}
// File: contracts/zeppelin/token/ERC20/ERC20Basic.sol
/**
* @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);
}
// File: contracts/zeppelin/math/SafeMath.sol
/**
* @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;
}
}
// File: contracts/zeppelin/token/ERC20/BasicToken.sol
/**
* @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];
}
}
// File: contracts/interface/ISeizable.sol
/**
* @title ISeizable
* @dev ISeizable interface
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
**/
contract ISeizable {
function seize(address _account, uint256 _value) public;
event Seize(address account, uint256 amount);
}
// File: contracts/zeppelin/ownership/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 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.
*/
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;
}
}
// File: contracts/Authority.sol
/**
* @title Authority
* @dev The Authority contract has an authority address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
* Authority means to represent a legal entity that is entitled to specific rights
*
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
*
* Error messages
* AU01: Message sender must be an authority
*/
contract Authority is Ownable {
address authority;
/**
* @dev Throws if called by any account other than the authority.
*/
modifier onlyAuthority {
require(msg.sender == authority, "AU01");
_;
}
/**
* @dev return the address associated to the authority
*/
function authorityAddress() public view returns (address) {
return authority;
}
/**
* @dev rdefines an authority
* @param _name the authority name
* @param _address the authority address.
*/
function defineAuthority(string _name, address _address) public onlyOwner {
emit AuthorityDefined(_name, _address);
authority = _address;
}
event AuthorityDefined(
string name,
address _address
);
}
// File: contracts/token/component/SeizableToken.sol
/**
* @title SeizableToken
* @dev BasicToken contract which allows owner to seize accounts
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
*
* Error messages
* ST01: Owner cannot seize itself
*/
contract SeizableToken is BasicToken, Authority, ISeizable {
using SafeMath for uint256;
// Although very unlikely, the value below may overflow.
// This contract and its children should expect it to happened and consider
// this value as only the first 256 bits of the complete value.
uint256 public allTimeSeized = 0; // overflow may happend
/**
* @dev called by the owner to seize value from the account
*/
function seize(address _account, uint256 _value)
public onlyAuthority
{
require(_account != owner, "ST01");
balances[_account] = balances[_account].sub(_value);
balances[authority] = balances[authority].add(_value);
allTimeSeized += _value;
emit Seize(_account, _value);
}
}
// File: contracts/zeppelin/token/ERC20/ERC20.sol
/**
* @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
);
}
// File: contracts/zeppelin/token/ERC20/StandardToken.sol
/**
* @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;
}
}
// File: contracts/interface/IProvableOwnership.sol
/**
* @title IProvableOwnership
* @dev IProvableOwnership interface which describe proof of ownership.
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
**/
contract IProvableOwnership {
function proofLength(address _holder) public view returns (uint256);
function proofAmount(address _holder, uint256 _proofId)
public view returns (uint256);
function proofDateFrom(address _holder, uint256 _proofId)
public view returns (uint256);
function proofDateTo(address _holder, uint256 _proofId)
public view returns (uint256);
function createProof(address _holder) public;
function checkProof(address _holder, uint256 _proofId, uint256 _at)
public view returns (uint256);
function transferWithProofs(
address _to,
uint256 _value,
bool _proofFrom,
bool _proofTo
) public returns (bool);
function transferFromWithProofs(
address _from,
address _to,
uint256 _value,
bool _proofFrom,
bool _proofTo
) public returns (bool);
event ProofOfOwnership(address indexed holder, uint256 proofId);
}
// File: contracts/interface/IAuditableToken.sol
/**
* @title IAuditableToken
* @dev IAuditableToken interface describing the audited data
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
**/
contract IAuditableToken {
function lastTransactionAt(address _address) public view returns (uint256);
function lastReceivedAt(address _address) public view returns (uint256);
function lastSentAt(address _address) public view returns (uint256);
function transactionCount(address _address) public view returns (uint256);
function receivedCount(address _address) public view returns (uint256);
function sentCount(address _address) public view returns (uint256);
function totalReceivedAmount(address _address) public view returns (uint256);
function totalSentAmount(address _address) public view returns (uint256);
}
// File: contracts/token/component/AuditableToken.sol
/**
* @title AuditableToken
* @dev AuditableToken contract
* AuditableToken provides transaction data which can be used
* in other smart contracts
*
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
**/
contract AuditableToken is IAuditableToken, StandardToken {
// Although very unlikely, the following values below may overflow:
// receivedCount, sentCount, totalReceivedAmount, totalSentAmount
// This contract and its children should expect it to happen and consider
// these values as only the first 256 bits of the complete value.
struct Audit {
uint256 createdAt;
uint256 lastReceivedAt;
uint256 lastSentAt;
uint256 receivedCount; // potential overflow
uint256 sentCount; // poential overflow
uint256 totalReceivedAmount; // potential overflow
uint256 totalSentAmount; // potential overflow
}
mapping(address => Audit) internal audits;
/**
* @dev Time of the creation of the audit struct
*/
function auditCreatedAt(address _address) public view returns (uint256) {
return audits[_address].createdAt;
}
/**
* @dev Time of the last transaction
*/
function lastTransactionAt(address _address) public view returns (uint256) {
return ( audits[_address].lastReceivedAt > audits[_address].lastSentAt ) ?
audits[_address].lastReceivedAt : audits[_address].lastSentAt;
}
/**
* @dev Time of the last received transaction
*/
function lastReceivedAt(address _address) public view returns (uint256) {
return audits[_address].lastReceivedAt;
}
/**
* @dev Time of the last sent transaction
*/
function lastSentAt(address _address) public view returns (uint256) {
return audits[_address].lastSentAt;
}
/**
* @dev Count of transactions
*/
function transactionCount(address _address) public view returns (uint256) {
return audits[_address].receivedCount + audits[_address].sentCount;
}
/**
* @dev Count of received transactions
*/
function receivedCount(address _address) public view returns (uint256) {
return audits[_address].receivedCount;
}
/**
* @dev Count of sent transactions
*/
function sentCount(address _address) public view returns (uint256) {
return audits[_address].sentCount;
}
/**
* @dev All time received
*/
function totalReceivedAmount(address _address)
public view returns (uint256)
{
return audits[_address].totalReceivedAmount;
}
/**
* @dev All time sent
*/
function totalSentAmount(address _address) public view returns (uint256) {
return audits[_address].totalSentAmount;
}
/**
* @dev Overriden transfer function
*/
function transfer(address _to, uint256 _value) public returns (bool) {
if (!super.transfer(_to, _value)) {
return false;
}
updateAudit(msg.sender, _to, _value);
return true;
}
/**
* @dev Overriden transferFrom function
*/
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool)
{
if (!super.transferFrom(_from, _to, _value)) {
return false;
}
updateAudit(_from, _to, _value);
return true;
}
/**
* @dev currentTime()
*/
function currentTime() internal view returns (uint256) {
// solium-disable-next-line security/no-block-members
return now;
}
/**
* @dev Update audit data
*/
function updateAudit(address _sender, address _receiver, uint256 _value)
private returns (uint256)
{
Audit storage senderAudit = audits[_sender];
senderAudit.lastSentAt = currentTime();
senderAudit.sentCount++;
senderAudit.totalSentAmount += _value;
if (senderAudit.createdAt == 0) {
senderAudit.createdAt = currentTime();
}
Audit storage receiverAudit = audits[_receiver];
receiverAudit.lastReceivedAt = currentTime();
receiverAudit.receivedCount++;
receiverAudit.totalReceivedAmount += _value;
if (receiverAudit.createdAt == 0) {
receiverAudit.createdAt = currentTime();
}
}
}
// File: contracts/token/component/ProvableOwnershipToken.sol
/**
* @title ProvableOwnershipToken
* @dev ProvableOwnershipToken is a StandardToken
* with ability to record a proof of ownership
*
* When desired a proof of ownership can be generated.
* The proof is stored within the contract.
* A proofId is then returned.
* The proof can later be used to retrieve the amount needed.
*
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
**/
contract ProvableOwnershipToken is IProvableOwnership, AuditableToken, Ownable {
struct Proof {
uint256 amount;
uint256 dateFrom;
uint256 dateTo;
}
mapping(address => mapping(uint256 => Proof)) internal proofs;
mapping(address => uint256) internal proofLengths;
/**
* @dev number of proof stored in the contract
*/
function proofLength(address _holder) public view returns (uint256) {
return proofLengths[_holder];
}
/**
* @dev amount contains for the proofId reccord
*/
function proofAmount(address _holder, uint256 _proofId)
public view returns (uint256)
{
return proofs[_holder][_proofId].amount;
}
/**
* @dev date from which the proof is valid
*/
function proofDateFrom(address _holder, uint256 _proofId)
public view returns (uint256)
{
return proofs[_holder][_proofId].dateFrom;
}
/**
* @dev date until the proof is valid
*/
function proofDateTo(address _holder, uint256 _proofId)
public view returns (uint256)
{
return proofs[_holder][_proofId].dateTo;
}
/**
* @dev called to challenge a proof at a point in the past
* Return the amount tokens owned by the proof owner at that time
*/
function checkProof(address _holder, uint256 _proofId, uint256 _at)
public view returns (uint256)
{
if (_proofId < proofLengths[_holder]) {
Proof storage proof = proofs[_holder][_proofId];
if (proof.dateFrom <= _at && _at <= proof.dateTo) {
return proof.amount;
}
}
return 0;
}
/**
* @dev called to create a proof of token ownership
*/
function createProof(address _holder) public {
createProofInternal(
_holder,
balanceOf(_holder),
lastTransactionAt(_holder)
);
}
/**
* @dev transfer function with also create a proof of ownership to any of the participants
* @param _proofSender if true a proof will be created for the sender
* @param _proofReceiver if true a proof will be created for the receiver
*/
function transferWithProofs(
address _to,
uint256 _value,
bool _proofSender,
bool _proofReceiver
) public returns (bool)
{
uint256 balanceBeforeFrom = balanceOf(msg.sender);
uint256 beforeFrom = lastTransactionAt(msg.sender);
uint256 balanceBeforeTo = balanceOf(_to);
uint256 beforeTo = lastTransactionAt(_to);
if (!super.transfer(_to, _value)) {
return false;
}
transferPostProcessing(
msg.sender,
balanceBeforeFrom,
beforeFrom,
_proofSender
);
transferPostProcessing(
_to,
balanceBeforeTo,
beforeTo,
_proofReceiver
);
return true;
}
/**
* @dev transfer function with also create a proof of ownership to any of the participants
* @param _proofSender if true a proof will be created for the sender
* @param _proofReceiver if true a proof will be created for the receiver
*/
function transferFromWithProofs(
address _from,
address _to,
uint256 _value,
bool _proofSender, bool _proofReceiver)
public returns (bool)
{
uint256 balanceBeforeFrom = balanceOf(_from);
uint256 beforeFrom = lastTransactionAt(_from);
uint256 balanceBeforeTo = balanceOf(_to);
uint256 beforeTo = lastTransactionAt(_to);
if (!super.transferFrom(_from, _to, _value)) {
return false;
}
transferPostProcessing(
_from,
balanceBeforeFrom,
beforeFrom,
_proofSender
);
transferPostProcessing(
_to,
balanceBeforeTo,
beforeTo,
_proofReceiver
);
return true;
}
/**
* @dev can be used to force create a proof (with a fake amount potentially !)
* Only usable by child contract internaly
*/
function createProofInternal(
address _holder, uint256 _amount, uint256 _from) internal
{
uint proofId = proofLengths[_holder];
// solium-disable-next-line security/no-block-members
proofs[_holder][proofId] = Proof(_amount, _from, currentTime());
proofLengths[_holder] = proofId+1;
emit ProofOfOwnership(_holder, proofId);
}
/**
* @dev private function updating contract state after a transfer operation
*/
function transferPostProcessing(
address _holder,
uint256 _balanceBefore,
uint256 _before,
bool _proof) private
{
if (_proof) {
createProofInternal(_holder, _balanceBefore, _before);
}
}
event ProofOfOwnership(address indexed holder, uint256 proofId);
}
// File: contracts/interface/IClaimable.sol
/**
* @title IClaimable
* @dev IClaimable interface
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
**/
interface IClaimable {
function hasClaimsSince(address _address, uint256 at)
external view returns (bool);
}
// File: contracts/interface/IWithClaims.sol
/**
* @title IWithClaims
* @dev IWithClaims interface
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
**/
contract IWithClaims {
function claimableLength() public view returns (uint256);
function claimable(uint256 _claimableId) public view returns (IClaimable);
function hasClaims(address _holder) public view returns (bool);
function defineClaimables(IClaimable[] _claimables) public;
event ClaimablesDefined(uint256 count);
}
// File: contracts/token/component/TokenWithClaims.sol
/**
* @title TokenWithClaims
* @dev TokenWithClaims contract
* TokenWithClaims is a token that will create a
* proofOfOwnership during transfers if a claim can be made.
* Holder may ask for the claim later using the proofOfOwnership
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
*
* Error messages
* E01: Claimable address must be defined
* E02: Claimables parameter must not be empty
* E03: Claimable does not exist
**/
contract TokenWithClaims is IWithClaims, ProvableOwnershipToken {
IClaimable[] claimables;
/**
* @dev Constructor
*/
constructor(IClaimable[] _claimables) public {
claimables = _claimables;
}
/**
* @dev Returns the number of claimables
*/
function claimableLength() public view returns (uint256) {
return claimables.length;
}
/**
* @dev Returns the Claimable associated to the specified claimableId
*/
function claimable(uint256 _claimableId) public view returns (IClaimable) {
return claimables[_claimableId];
}
/**
* @dev Returns true if there are any claims associated to this token
* to be made at this time for the _holder
*/
function hasClaims(address _holder) public view returns (bool) {
uint256 lastTransaction = lastTransactionAt(_holder);
for (uint256 i = 0; i < claimables.length; i++) {
if (claimables[i].hasClaimsSince(_holder, lastTransaction)) {
return true;
}
}
return false;
}
/**
* @dev Override the transfer function with transferWithProofs
* A proof of ownership will be made if any claims can be made by the participants
*/
function transfer(address _to, uint256 _value) public returns (bool) {
bool proofFrom = hasClaims(msg.sender);
bool proofTo = hasClaims(_to);
return super.transferWithProofs(
_to,
_value,
proofFrom,
proofTo
);
}
/**
* @dev Override the transfer function with transferWithProofs
* A proof of ownership will be made if any claims can be made by the participants
*/
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool)
{
bool proofFrom = hasClaims(_from);
bool proofTo = hasClaims(_to);
return super.transferFromWithProofs(
_from,
_to,
_value,
proofFrom,
proofTo
);
}
/**
* @dev transfer with proofs
*/
function transferWithProofs(
address _to,
uint256 _value,
bool _proofFrom,
bool _proofTo
) public returns (bool)
{
bool proofFrom = _proofFrom || hasClaims(msg.sender);
bool proofTo = _proofTo || hasClaims(_to);
return super.transferWithProofs(
_to,
_value,
proofFrom,
proofTo
);
}
/**
* @dev transfer from with proofs
*/
function transferFromWithProofs(
address _from,
address _to,
uint256 _value,
bool _proofFrom,
bool _proofTo
) public returns (bool)
{
bool proofFrom = _proofFrom || hasClaims(_from);
bool proofTo = _proofTo || hasClaims(_to);
return super.transferFromWithProofs(
_from,
_to,
_value,
proofFrom,
proofTo
);
}
/**
* @dev define claimables contract to this token
*/
function defineClaimables(IClaimable[] _claimables) public onlyOwner {
claimables = _claimables;
emit ClaimablesDefined(claimables.length);
}
}
// File: contracts/interface/IRule.sol
/**
* @title IRule
* @dev IRule interface
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
**/
interface IRule {
function isAddressValid(address _address) external view returns (bool);
function isTransferValid(address _from, address _to, uint256 _amount)
external view returns (bool);
}
// File: contracts/interface/IWithRules.sol
/**
* @title IWithRules
* @dev IWithRules interface
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
**/
contract IWithRules {
function ruleLength() public view returns (uint256);
function rule(uint256 _ruleId) public view returns (IRule);
function validateAddress(address _address) public view returns (bool);
function validateTransfer(address _from, address _to, uint256 _amount)
public view returns (bool);
function defineRules(IRule[] _rules) public;
event RulesDefined(uint256 count);
}
// File: contracts/rule/WithRules.sol
/**
* @title WithRules
* @dev WithRules contract allows inheriting contract to use a set of validation rules
* @dev contract owner may add or remove rules
*
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
*
* Error messages
* WR01: The rules rejected this address
* WR02: The rules rejected the transfer
**/
contract WithRules is IWithRules, Ownable {
IRule[] internal rules;
/**
* @dev Constructor
*/
constructor(IRule[] _rules) public {
rules = _rules;
}
/**
* @dev Returns the number of rules
*/
function ruleLength() public view returns (uint256) {
return rules.length;
}
/**
* @dev Returns the Rule associated to the specified ruleId
*/
function rule(uint256 _ruleId) public view returns (IRule) {
return rules[_ruleId];
}
/**
* @dev Check if the rules are valid for an address
*/
function validateAddress(address _address) public view returns (bool) {
for (uint256 i = 0; i < rules.length; i++) {
if (!rules[i].isAddressValid(_address)) {
return false;
}
}
return true;
}
/**
* @dev Check if the rules are valid
*/
function validateTransfer(address _from, address _to, uint256 _amount)
public view returns (bool)
{
for (uint256 i = 0; i < rules.length; i++) {
if (!rules[i].isTransferValid(_from, _to, _amount)) {
return false;
}
}
return true;
}
/**
* @dev Modifier to make functions callable
* only when participants follow rules
*/
modifier whenAddressRulesAreValid(address _address) {
require(validateAddress(_address), "WR01");
_;
}
/**
* @dev Modifier to make transfer functions callable
* only when participants follow rules
*/
modifier whenTransferRulesAreValid(
address _from,
address _to,
uint256 _amount)
{
require(validateTransfer(_from, _to, _amount), "WR02");
_;
}
/**
* @dev Define rules to the token
*/
function defineRules(IRule[] _rules) public onlyOwner {
rules = _rules;
emit RulesDefined(rules.length);
}
}
// File: contracts/token/component/TokenWithRules.sol
/**
* @title TokenWithRules
* @dev TokenWithRules contract
* TokenWithRules is a token that will apply
* rules restricting transferability
*
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
*
**/
contract TokenWithRules is StandardToken, WithRules {
/**
* @dev Constructor
*/
constructor(IRule[] _rules) public WithRules(_rules) { }
/**
* @dev Overriden transfer function
*/
function transfer(address _to, uint256 _value)
public whenTransferRulesAreValid(msg.sender, _to, _value)
returns (bool)
{
return super.transfer(_to, _value);
}
/**
* @dev Overriden transferFrom function
*/
function transferFrom(address _from, address _to, uint256 _value)
public whenTransferRulesAreValid(_from, _to, _value)
whenAddressRulesAreValid(msg.sender)
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
}
// File: contracts/token/BridgeToken.sol
/**
* @title BridgeToken
* @dev BridgeToken contract
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
*/
contract BridgeToken is TokenWithRules, TokenWithClaims, SeizableToken {
string public name;
string public symbol;
/**
* @dev constructor
*/
constructor(string _name, string _symbol)
TokenWithRules(new IRule[](0))
TokenWithClaims(new IClaimable[](0)) public
{
name = _name;
symbol = _symbol;
}
}
// File: contracts/governance/BoardSig.sol
/**
* @title BoardSig
* @dev BoardSig contract
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
*
* @notice Swissquote Bank SA solely is entitled to the GNU LGPL.
* @notice Any other party is subject to the copyright mentioned in the software.
*
* Error messages
*/
contract BoardSig is MultiSig {
bytes32 public constant TOKENIZE = keccak256("TOKENIZE");
string public companyName;
string public country;
string public registeredNumber;
BridgeToken public token;
/**
* @dev constructor function
*/
constructor(address[] _addresses, uint8 _threshold) public
MultiSig(_addresses, _threshold)
{
}
/**
* @dev returns hash of hashed "TOKENIZE"+ token address + document hash
*/
function tokenizeHash(BridgeToken _token, bytes32 _hash)
public pure returns (bytes32)
{
return keccak256(
abi.encode(TOKENIZE, address(_token), _hash)
);
}
/**
* @dev tokenize shares
*/
function tokenizeShares(
BridgeToken _token,
bytes32 _hash,
bytes32[] _sigR,
bytes32[] _sigS,
uint8[] _sigV) public
thresholdRequired(address(this), 0,
abi.encodePacked(tokenizeHash(_token, _hash)),
0, threshold, _sigR, _sigS, _sigV)
{
updateReplayProtection();
token = _token;
emit ShareTokenization(_token, _hash);
}
/**
* @dev add board meeting
*/
function addBoardMeeting(
bytes32 _hash,
bytes32[] _sigR,
bytes32[] _sigS,
uint8[] _sigV) public
thresholdRequired(address(this), 0,
abi.encodePacked(_hash),
0, threshold, _sigR, _sigS, _sigV)
{
emit BoardMeetingHash(_hash);
}
event ShareTokenization(BridgeToken token, bytes32 hash);
event BoardMeetingHash(bytes32 hash);
}
// File: contracts/mps/MPSBoardSig.sol
/**
* @title MPSBoardSig
* @dev MPSBoardSig contract
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
*
* Error messages
*/
contract MPSBoardSig is BoardSig {
string public companyName = "MtPelerin Group SA";
string public country = "Switzerland";
string public registeredNumber = "CHE-188.552.084";
/**
* @dev constructor function
*/
constructor(address[] _addresses, uint8 _threshold) public
BoardSig(_addresses, _threshold)
{
}
} | Time of the last received transaction/ | function lastReceivedAt(address _address) public view returns (uint256) {
return audits[_address].lastReceivedAt;
}
| 1,773,392 |
// File: @openzeppelin/contracts/math/Math.sol
pragma solidity ^0.5.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/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/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/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @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 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");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.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 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");
}
}
}
// 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: contracts/strategies/curve/interfaces/Gauge.sol
pragma solidity 0.5.16;
interface Gauge {
function deposit(uint) external;
function balanceOf(address) external view returns (uint);
function withdraw(uint) external;
function user_checkpoint(address) external;
}
interface VotingEscrow {
function create_lock(uint256 v, uint256 time) external;
function increase_amount(uint256 _value) external;
function increase_unlock_time(uint256 _unlock_time) external;
function withdraw() external;
}
interface Mintr {
function mint(address) external;
}
// File: contracts/strategies/curve/interfaces/ICurveFi.sol
pragma solidity 0.5.16;
interface ICurveFi {
function get_virtual_price() external view returns (uint);
function add_liquidity(
uint256[4] calldata amounts,
uint256 min_mint_amount
) external;
function remove_liquidity_imbalance(
uint256[4] calldata amounts,
uint256 max_burn_amount
) external;
function remove_liquidity(
uint256 _amount,
uint256[4] calldata amounts
) external;
function exchange(
int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount
) external;
function calc_token_amount(
uint256[4] calldata amounts,
bool deposit
) external view returns(uint);
}
// File: contracts/strategies/curve/interfaces/yVault.sol
pragma solidity 0.5.16;
interface yERC20 {
function deposit(uint256 _amount) external;
function withdraw(uint256 _amount) external;
function getPricePerFullShare() external view returns (uint256);
}
// File: contracts/strategies/curve/interfaces/IPriceConvertor.sol
pragma solidity 0.5.16;
interface IPriceConvertor {
function yCrvToUnderlying(uint256 _token_amount, uint256 i) external view returns (uint256);
}
// File: contracts/hardworkInterface/IVault.sol
pragma solidity 0.5.16;
interface IVault {
// the IERC20 part is the share
function underlyingBalanceInVault() external view returns (uint256);
function underlyingBalanceWithInvestment() external view returns (uint256);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function strategy() external view returns (address);
function setStrategy(address _strategy) external;
function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external;
function deposit(uint256 amountWei) external;
function depositFor(uint256 amountWei, address holder) external;
function withdrawAll() external;
function withdraw(uint256 numberOfShares) external;
function getPricePerFullShare() external view returns (uint256);
function underlyingBalanceWithInvestmentForHolder(address holder) view external returns (uint256);
// hard work should be callable only by the controller (by the hard worker) or by governance
function doHardWork() external;
function rebalance() external;
}
// File: contracts/hardworkInterface/IController.sol
pragma solidity 0.5.16;
interface IController {
// [Grey list]
// An EOA can safely interact with the system no matter what.
// If you're using Metamask, you're using an EOA.
// Only smart contracts may be affected by this grey list.
//
// This contract will not be able to ban any EOA from the system
// even if an EOA is being added to the greyList, he/she will still be able
// to interact with the whole system as if nothing happened.
// Only smart contracts will be affected by being added to the greyList.
// This grey list is only used in Vault.sol, see the code there for reference
function greyList(address _target) external returns(bool);
function addVaultAndStrategy(address _vault, address _strategy) external;
function doHardWork(address _vault) external;
function hasVault(address _vault) external returns(bool);
function salvage(address _token, uint256 amount) external;
function salvageStrategy(address _strategy, address _token, uint256 amount) external;
function notifyFee(address _underlying, uint256 fee) external;
function profitSharingNumerator() external view returns (uint256);
function profitSharingDenominator() external view returns (uint256);
}
// File: contracts/hardworkInterface/IStrategy.sol
pragma solidity 0.5.16;
interface IStrategy {
function unsalvagableTokens(address tokens) external view returns (bool);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function vault() external view returns (address);
function withdrawAllToVault() external;
function withdrawToVault(uint256 amount) external;
function investedUnderlyingBalance() external view returns (uint256); // itsNotMuch()
// should only be called by controller
function salvage(address recipient, address token, uint256 amount) external;
function doHardWork() external;
function depositArbCheck() external view returns(bool);
}
// File: contracts/Storage.sol
pragma solidity 0.5.16;
contract Storage {
address public governance;
address public controller;
constructor() public {
governance = msg.sender;
}
modifier onlyGovernance() {
require(isGovernance(msg.sender), "Not governance");
_;
}
function setGovernance(address _governance) public onlyGovernance {
require(_governance != address(0), "new governance shouldn't be empty");
governance = _governance;
}
function setController(address _controller) public onlyGovernance {
require(_controller != address(0), "new controller shouldn't be empty");
controller = _controller;
}
function isGovernance(address account) public view returns (bool) {
return account == governance;
}
function isController(address account) public view returns (bool) {
return account == controller;
}
}
// File: contracts/Governable.sol
pragma solidity 0.5.16;
contract Governable {
Storage public store;
constructor(address _store) public {
require(_store != address(0), "new storage shouldn't be empty");
store = Storage(_store);
}
modifier onlyGovernance() {
require(store.isGovernance(msg.sender), "Not governance");
_;
}
function setStorage(address _store) public onlyGovernance {
require(_store != address(0), "new storage shouldn't be empty");
store = Storage(_store);
}
function governance() public view returns (address) {
return store.governance();
}
}
// File: contracts/Controllable.sol
pragma solidity 0.5.16;
contract Controllable is Governable {
constructor(address _storage) Governable(_storage) public {
}
modifier onlyController() {
require(store.isController(msg.sender), "Not a controller");
_;
}
modifier onlyControllerOrGovernance(){
require((store.isController(msg.sender) || store.isGovernance(msg.sender)),
"The caller must be controller or governance");
_;
}
function controller() public view returns (address) {
return store.controller();
}
}
// File: contracts/strategies/curve/CRVStrategyStable.sol
pragma solidity 0.5.16;
/**
* The goal of this strategy is to take a stable asset (DAI, USDC, USDT), turn it into ycrv using
* the curve mechanisms, and supply ycrv into the ycrv vault. The ycrv vault will likely not have
* a reward token distribution pool to avoid double dipping. All the calls to functions from this
* strategy will be routed to the controller which should then call the respective methods on the
* ycrv vault. This strategy will not be liquidating any yield crops (CRV), because the strategy
* of the ycrv vault will do that for us.
*/
contract CRVStrategyStable is IStrategy, Controllable {
enum TokenIndex {DAI, USDC, USDT}
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
// underlying asset
address public underlying;
// the matching enum record used to determine the index
TokenIndex tokenIndex;
// our vault holding the underlying asset
address public vault;
// the y-vault (yield tokens from Curve) corresponding to our asset
address public yVault;
// our vault for depositing the yCRV tokens
address public ycrvVault;
// the address of yCRV token
address public ycrv;
// the address of the Curve protocol
address public curve;
// the address of the IPriceConvertor
address public convertor;
// these tokens cannot be claimed by the governance
mapping(address => bool) public unsalvagableTokens;
uint256 public curvePriceCheckpoint;
uint256 public ycrvUnit;
uint256 public arbTolerance = 3;
modifier restricted() {
require(msg.sender == vault || msg.sender == controller()
|| msg.sender == governance(),
"The sender has to be the controller, governance, or vault");
_;
}
constructor(
address _storage,
address _underlying,
address _vault,
address _ycrvVault,
address _yVault,
uint256 _tokenIndex,
address _ycrv,
address _curveProtocol,
address _convertor
)
Controllable(_storage) public {
vault = _vault;
ycrvVault = _ycrvVault;
underlying = _underlying;
tokenIndex = TokenIndex(_tokenIndex);
yVault = _yVault;
ycrv = _ycrv;
curve = _curveProtocol;
convertor = _convertor;
// set these tokens to be not salvageable
unsalvagableTokens[underlying] = true;
unsalvagableTokens[yVault] = true;
unsalvagableTokens[ycrv] = true;
unsalvagableTokens[ycrvVault] = true;
ycrvUnit = 10 ** 18;
// starting with a stable price, the mainnet will override this value
curvePriceCheckpoint = ycrvUnit;
}
function depositArbCheck() public view returns(bool) {
uint256 currentPrice = underlyingValueFromYCrv(ycrvUnit);
if (currentPrice > curvePriceCheckpoint) {
return currentPrice.mul(100).div(curvePriceCheckpoint) > 100 - arbTolerance;
} else {
return curvePriceCheckpoint.mul(100).div(currentPrice) > 100 - arbTolerance;
}
}
function setArbTolerance(uint256 tolerance) external onlyGovernance {
require(tolerance <= 100, "at most 100");
arbTolerance = tolerance;
}
/**
* Uses the Curve protocol to convert the underlying asset into yAsset and then to yCRV.
*/
function yCurveFromUnderlying() internal {
// convert underlying asset to yAsset
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
IERC20(underlying).safeApprove(yVault, 0);
IERC20(underlying).safeApprove(yVault, underlyingBalance);
yERC20(yVault).deposit(underlyingBalance);
}
// convert yAsset to yCRV
uint256 yBalance = IERC20(yVault).balanceOf(address(this));
if (yBalance > 0) {
IERC20(yVault).safeApprove(curve, 0);
IERC20(yVault).safeApprove(curve, yBalance);
// we can accept 0 as minimum because this is called only by a trusted role
uint256 minimum = 0;
uint256[4] memory coinAmounts = wrapCoinAmount(yBalance);
ICurveFi(curve).add_liquidity(
coinAmounts, minimum
);
}
// now we have yCRV
}
/**
* Uses the Curve protocol to convert the yCRV back into the underlying asset. If it cannot acquire
* the limit amount, it will acquire the maximum it can.
*/
function yCurveToUnderlying(uint256 underlyingLimit) internal {
uint256 ycrvBalance = IERC20(ycrv).balanceOf(address(this));
// this is the maximum number of y-tokens we can get for our yCRV
uint256 yTokenMaximumAmount = yTokenValueFromYCrv(ycrvBalance);
if (yTokenMaximumAmount == 0) {
return;
}
// ensure that we will not overflow in the conversion
uint256 yTokenDesiredAmount = underlyingLimit == uint256(~0) ?
yTokenMaximumAmount : yTokenValueFromUnderlying(underlyingLimit);
uint256[4] memory yTokenAmounts = wrapCoinAmount(
Math.min(yTokenMaximumAmount, yTokenDesiredAmount));
uint256 yUnderlyingBalanceBefore = IERC20(yVault).balanceOf(address(this));
IERC20(ycrv).safeApprove(curve, 0);
IERC20(ycrv).safeApprove(curve, ycrvBalance);
ICurveFi(curve).remove_liquidity_imbalance(
yTokenAmounts, ycrvBalance
);
// now we have yUnderlying asset
uint256 yUnderlyingBalanceAfter = IERC20(yVault).balanceOf(address(this));
if (yUnderlyingBalanceAfter > yUnderlyingBalanceBefore) {
// we received new yUnderlying tokens for yCRV
yERC20(yVault).withdraw(yUnderlyingBalanceAfter.sub(yUnderlyingBalanceBefore));
}
}
/**
* Withdraws an underlying asset from the strategy to the vault in the specified amount by asking
* the yCRV vault for yCRV (currently all of it), and then removing imbalanced liquidity from
* the Curve protocol. The rest is deposited back to the yCRV vault. If the amount requested cannot
* be obtained, the method will get as much as we have.
*/
function withdrawToVault(uint256 amountUnderlying) external restricted {
// If we want to be more accurate, we need to calculate how much yCRV we will need here
uint256 shares = IERC20(ycrvVault).balanceOf(address(this));
IVault(ycrvVault).withdraw(shares);
yCurveToUnderlying(amountUnderlying);
// we can transfer the asset to the vault
uint256 actualBalance = IERC20(underlying).balanceOf(address(this));
if (actualBalance > 0) {
IERC20(underlying).safeTransfer(vault, Math.min(amountUnderlying, actualBalance));
}
// invest back the rest
investAllUnderlying();
}
/**
* Withdraws all assets from the vault. We ask the yCRV vault to give us our entire yCRV balance
* and then convert it to the underlying asset using the Curve protocol.
*/
function withdrawAllToVault() external restricted {
uint256 shares = IERC20(ycrvVault).balanceOf(address(this));
IVault(ycrvVault).withdraw(shares);
// withdraw everything until there is only dust left
yCurveToUnderlying(uint256(~0));
uint256 actualBalance = IERC20(underlying).balanceOf(address(this));
if (actualBalance > 0) {
IERC20(underlying).safeTransfer(vault, actualBalance);
}
}
/**
* Invests all underlying assets into our yCRV vault.
*/
function investAllUnderlying() internal {
// convert the entire balance not yet invested into yCRV first
yCurveFromUnderlying();
// then deposit into the yCRV vault
uint256 ycrvBalance = IERC20(ycrv).balanceOf(address(this));
if (ycrvBalance > 0) {
IERC20(ycrv).safeApprove(ycrvVault, 0);
IERC20(ycrv).safeApprove(ycrvVault, ycrvBalance);
// deposits the entire balance and also asks the vault to invest it (public function)
IVault(ycrvVault).deposit(ycrvBalance);
}
}
/**
* The hard work only invests all underlying assets, and then tells the controller to call hard
* work on the yCRV vault.
*/
function doHardWork() public restricted {
investAllUnderlying();
curvePriceCheckpoint = underlyingValueFromYCrv(ycrvUnit);
}
/**
* Salvages a token. We cannot salvage the shares in the yCRV pool, yCRV tokens, or underlying
* assets.
*/
function salvage(address recipient, address token, uint256 amount) public onlyGovernance {
// To make sure that governance cannot come in and take away the coins
require(!unsalvagableTokens[token], "token is defined as not salvageable");
IERC20(token).safeTransfer(recipient, amount);
}
/**
* Returns the underlying invested balance. This is the amount of yCRV that we are entitled to
* from the yCRV vault (based on the number of shares we currently have), converted to the
* underlying assets by the Curve protocol, plus the current balance of the underlying assets.
*/
function investedUnderlyingBalance() public view returns (uint256) {
uint256 shares = IERC20(ycrvVault).balanceOf(address(this));
uint256 price = IVault(ycrvVault).getPricePerFullShare();
// the price is in yCRV units, because this is a yCRV vault
// the multiplication doubles the number of decimals for shares, so we need to divide
// the precision is always 10 ** 18 as the yCRV vault has 18 decimals
uint256 precision = 10 ** 18;
uint256 ycrvBalance = shares.mul(price).div(precision);
// now we can convert the balance to the token amount
uint256 ycrvValue = underlyingValueFromYCrv(ycrvBalance);
return ycrvValue.add(IERC20(underlying).balanceOf(address(this)));
}
/**
* Returns the value of yCRV in underlying token accounting for slippage and fees.
*/
function yTokenValueFromYCrv(uint256 ycrvBalance) public view returns (uint256) {
return underlyingValueFromYCrv(ycrvBalance) // this is in DAI, we will convert to yDAI
.mul(10 ** 18)
.div(yERC20(yVault).getPricePerFullShare()); // function getPricePerFullShare() has 18 decimals for all tokens
}
/**
* Returns the value of yCRV in y-token (e.g., yCRV -> yDai) accounting for slippage and fees.
*/
function underlyingValueFromYCrv(uint256 ycrvBalance) public view returns (uint256) {
return IPriceConvertor(convertor).yCrvToUnderlying(ycrvBalance, uint256(tokenIndex));
}
/**
* Returns the value of the underlying token in yToken
*/
function yTokenValueFromUnderlying(uint256 amountUnderlying) public view returns (uint256) {
// 1 yToken = this much underlying, 10 ** 18 precision for all tokens
return amountUnderlying
.mul(10 ** 18)
.div(yERC20(yVault).getPricePerFullShare());
}
/**
* Wraps the coin amount in the array for interacting with the Curve protocol
*/
function wrapCoinAmount(uint256 amount) internal view returns (uint256[4] memory) {
uint256[4] memory amounts = [uint256(0), uint256(0), uint256(0), uint256(0)];
amounts[uint56(tokenIndex)] = amount;
return amounts;
}
/**
* Replaces the price convertor
*/
function setConvertor(address _convertor) public onlyGovernance {
// different price conversion from yCurve to yToken can help in emergency recovery situation
// or if there is a bug discovered in the price computation
convertor = _convertor;
}
}
// File: contracts/strategies/curve/PriceConvertor.sol
pragma solidity 0.5.16;
interface IConvertor {
function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256);
}
contract PriceConvertor is IPriceConvertor {
IConvertor public zap = IConvertor(0xbBC81d23Ea2c3ec7e56D39296F0cbB648873a5d3);
function yCrvToUnderlying(uint256 _token_amount, uint256 i) public view returns (uint256) {
// this returning the DAI amount, not yDAI
return zap.calc_withdraw_one_coin(_token_amount, int128(i));
}
}
contract MockPriceConvertor is IPriceConvertor {
function yCrvToUnderlying(uint256 _token_amount, uint256 /* i */) public view returns (uint256) {
// counting 1:1
return _token_amount;
}
}
// File: contracts/strategies/curve/CRVStrategyStableMainnet.sol
pragma solidity 0.5.16;
/**
* Adds the mainnet addresses to the CRVStrategyStable
*/
contract CRVStrategyStableMainnet is CRVStrategyStable {
// token addresses
// y-addresses are taken from: https://docs.yearn.finance/yearn.finance/yearn-1
address constant public dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
address constant public ydai = address(0x16de59092dAE5CcF4A1E6439D611fd0653f0Bd01);
address constant public usdc = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
address constant public yusdc = address(0xd6aD7a6750A7593E092a9B218d66C0A814a3436e);
address constant public usdt = address(0xdAC17F958D2ee523a2206206994597C13D831ec7);
address constant public yusdt = address(0x83f798e925BcD4017Eb265844FDDAbb448f1707D);
// pre-defined constant mapping: underlying -> y-token
mapping(address => address) public yVaults;
// yDAIyUSDCyUSDTyTUSD
address constant public __ycrv = address(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8);
// protocols
address constant public __curve = address(0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51);
constructor(
address _storage,
address _underlying,
address _vault,
address _ycrvVault
)
CRVStrategyStable(_storage, _underlying, _vault, _ycrvVault, address(0), 0,
__ycrv,
__curve,
address(0)
)
public {
yVaults[dai] = ydai;
yVaults[usdc] = yusdc;
yVaults[usdt] = yusdt;
yVault = yVaults[underlying];
require(yVault != address(0), "underlying not supported: yVault is not defined");
if (_underlying == dai) {
tokenIndex = TokenIndex.DAI;
} else if (_underlying == usdc) {
tokenIndex = TokenIndex.USDC;
} else if (_underlying == usdt) {
tokenIndex = TokenIndex.USDT;
} else {
revert("What is this asset?");
}
convertor = address(new PriceConvertor());
curvePriceCheckpoint = underlyingValueFromYCrv(ycrvUnit);
}
} | Withdraws all assets from the vault. We ask the yCRV vault to give us our entire yCRV balance and then convert it to the underlying asset using the Curve protocol./ withdraw everything until there is only dust left | function withdrawAllToVault() external restricted {
uint256 shares = IERC20(ycrvVault).balanceOf(address(this));
IVault(ycrvVault).withdraw(shares);
yCurveToUnderlying(uint256(~0));
uint256 actualBalance = IERC20(underlying).balanceOf(address(this));
if (actualBalance > 0) {
IERC20(underlying).safeTransfer(vault, actualBalance);
}
}
| 6,814,839 |
/**
*Submitted for verification at Etherscan.io on 2022-03-31
*/
// SPDX-License-Identifier: MIT
pragma solidity =0.6.12;
//
/*
* @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;
}
}
//
//
/**
* @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;
}
}
//
/**
* @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);
}
}
}
}
//
/**
* @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);
}
//
/**
* @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");
}
}
}
//
// solhint-disable-next-line compiler-version
/**
* @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 !Address.isContract(address(this));
}
}
//
/**
* @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, Initializable {
address private _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 init(address sender) internal virtual initializer {
_owner = sender;
}
/**
* @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;
}
}
//
// MasterChef is the master of VEMP. He can make VEMP and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once VEMP is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChefAPE is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
uint256 rewardAPEDebt; // Reward debt in APE.
//
// We do some fancy math here. Basically, any point in time, the amount of VEMPs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accVEMPPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accVEMPPerShare` (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 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. VEMPs to distribute per block.
uint256 lastRewardBlock; // Last block number that VEMPs distribution occurs.
uint256 accVEMPPerShare; // Accumulated VEMPs per share, times 1e12. See below.
uint256 accAPEPerShare; // Accumulated APEs per share, times 1e12. See below.
uint256 lastTotalAPEReward; // last total rewards
uint256 lastAPERewardBalance; // last APE rewards tokens
uint256 totalAPEReward; // total APE rewards tokens
}
// The VEMP TOKEN!
IERC20 public VEMP;
// admin address.
address public adminaddr;
// VEMP tokens created per block.
uint256 public VEMPPerBlock;
// Bonus muliplier for early VEMP makers.
uint256 public constant BONUS_MULTIPLIER = 1;
// Info of each pool.
PoolInfo public poolInfo;
// Info of each user that stakes LP tokens.
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 VEMP mining starts.
uint256 public startBlock;
// total APE staked
uint256 public totalAPEStaked;
// total APE used for purchase land
uint256 public totalAPEUsedForPurchase = 0;
// withdraw status
bool public withdrawStatus;
// reward end status
bool public rewardEndStatus;
// reward end block number
uint256 public rewardEndBlock;
event Deposit(address indexed user, uint256 amount);
event Withdraw(address indexed user, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 amount);
event Set(uint256 allocPoint, bool overwrite);
event RewardEndStatus(bool rewardStatus, uint256 rewardEndBlock);
event RewardPerBlock(uint256 oldRewardPerBlock, uint256 newRewardPerBlock);
event AccessAPEToken(address indexed user, uint256 amount, uint256 totalAPEUsedForPurchase);
event AddAPETokensInPool(uint256 amount, uint256 totalAPEUsedForPurchase);
constructor() public {}
function initialize(
IERC20 _VEMP,
IERC20 _lpToken,
address _adminaddr,
uint256 _VEMPPerBlock,
uint256 _startBlock
) public initializer {
require(address(_VEMP) != address(0), "Invalid VEMP address");
require(address(_lpToken) != address(0), "Invalid lpToken address");
require(address(_adminaddr) != address(0), "Invalid admin address");
Ownable.init(_adminaddr);
VEMP = _VEMP;
adminaddr = _adminaddr;
VEMPPerBlock = _VEMPPerBlock;
startBlock = _startBlock;
withdrawStatus = false;
rewardEndStatus = false;
rewardEndBlock = 0;
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(100);
poolInfo.lpToken = _lpToken;
poolInfo.allocPoint = 100;
poolInfo.lastRewardBlock = lastRewardBlock;
poolInfo.accVEMPPerShare = 0;
poolInfo.accAPEPerShare = 0;
poolInfo.lastTotalAPEReward = 0;
poolInfo.lastAPERewardBalance = 0;
poolInfo.totalAPEReward = 0;
}
// Update the given pool's VEMP allocation point. Can only be called by the owner.
function set( uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
updatePool();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo.allocPoint).add(_allocPoint);
poolInfo.allocPoint = _allocPoint;
emit Set(_allocPoint, _withUpdate);
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) {
if (_to >= _from) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else {
return _from.sub(_to);
}
}
// View function to see pending VEMPs on frontend.
function pendingVEMP(address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo;
UserInfo storage user = userInfo[_user];
uint256 accVEMPPerShare = pool.accVEMPPerShare;
uint256 rewardBlockNumber = block.number;
if(rewardEndStatus != false) {
rewardBlockNumber = rewardEndBlock;
}
uint256 lpSupply = totalAPEStaked;
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, rewardBlockNumber);
uint256 VEMPReward = multiplier.mul(VEMPPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accVEMPPerShare = accVEMPPerShare.add(VEMPReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accVEMPPerShare).div(1e12).sub(user.rewardDebt);
}
// View function to see pending APEs on frontend.
function pendingAPE(address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo;
UserInfo storage user = userInfo[_user];
uint256 accAPEPerShare = pool.accAPEPerShare;
uint256 lpSupply = totalAPEStaked;
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 rewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase));
uint256 _totalReward = rewardBalance.sub(pool.lastAPERewardBalance);
accAPEPerShare = accAPEPerShare.add(_totalReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accAPEPerShare).div(1e12).sub(user.rewardAPEDebt);
}
// Update reward variables of the given pool to be up-to-date.
function updatePool() internal {
PoolInfo storage pool = poolInfo;
UserInfo storage user = userInfo[msg.sender];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 rewardBlockNumber = block.number;
if(rewardEndStatus != false) {
rewardBlockNumber = rewardEndBlock;
}
uint256 rewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase));
uint256 _totalReward = pool.totalAPEReward.add(rewardBalance.sub(pool.lastAPERewardBalance));
pool.lastAPERewardBalance = rewardBalance;
pool.totalAPEReward = _totalReward;
uint256 lpSupply = totalAPEStaked;
if (lpSupply == 0) {
pool.lastRewardBlock = rewardBlockNumber;
pool.accAPEPerShare = 0;
pool.lastTotalAPEReward = 0;
user.rewardAPEDebt = 0;
pool.lastAPERewardBalance = 0;
pool.totalAPEReward = 0;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, rewardBlockNumber);
uint256 VEMPReward = multiplier.mul(VEMPPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accVEMPPerShare = pool.accVEMPPerShare.add(VEMPReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = rewardBlockNumber;
uint256 reward = _totalReward.sub(pool.lastTotalAPEReward);
pool.accAPEPerShare = pool.accAPEPerShare.add(reward.mul(1e12).div(lpSupply));
pool.lastTotalAPEReward = _totalReward;
}
// Deposit LP tokens to MasterChef for VEMP allocation.
function deposit(uint256 _amount) public {
PoolInfo storage pool = poolInfo;
UserInfo storage user = userInfo[msg.sender];
updatePool();
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accVEMPPerShare).div(1e12).sub(user.rewardDebt);
safeVEMPTransfer(msg.sender, pending);
uint256 APEReward = user.amount.mul(pool.accAPEPerShare).div(1e12).sub(user.rewardAPEDebt);
pool.lpToken.safeTransfer(msg.sender, APEReward);
pool.lastAPERewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase));
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
totalAPEStaked = totalAPEStaked.add(_amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accVEMPPerShare).div(1e12);
user.rewardAPEDebt = user.amount.mul(pool.accAPEPerShare).div(1e12);
emit Deposit(msg.sender, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _amount) public {
require(withdrawStatus != true, "Withdraw not allowed");
PoolInfo storage pool = poolInfo;
UserInfo storage user = userInfo[msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool();
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accVEMPPerShare).div(1e12).sub(user.rewardDebt);
safeVEMPTransfer(msg.sender, pending);
uint256 APEReward = user.amount.mul(pool.accAPEPerShare).div(1e12).sub(user.rewardAPEDebt);
pool.lpToken.safeTransfer(msg.sender, APEReward);
pool.lastAPERewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase));
}
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accVEMPPerShare).div(1e12);
user.rewardAPEDebt = user.amount.mul(pool.accAPEPerShare).div(1e12);
totalAPEStaked = totalAPEStaked.sub(_amount);
pool.lpToken.safeTransfer(msg.sender, _amount);
emit Withdraw(msg.sender, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw() public {
require(withdrawStatus != true, "Withdraw not allowed");
PoolInfo storage pool = poolInfo;
UserInfo storage user = userInfo[msg.sender];
pool.lpToken.safeTransfer(msg.sender, user.amount);
totalAPEStaked = totalAPEStaked.sub(user.amount);
user.amount = 0;
user.rewardDebt = 0;
user.rewardAPEDebt = 0;
emit EmergencyWithdraw(msg.sender, user.amount);
}
// Safe VEMP transfer function, just in case if rounding error causes pool to not have enough VEMPs.
function safeVEMPTransfer(address _to, uint256 _amount) internal {
uint256 VEMPBal = VEMP.balanceOf(address(this));
if (_amount > VEMPBal) {
VEMP.transfer(_to, VEMPBal);
} else {
VEMP.transfer(_to, _amount);
}
}
// Earn APE tokens to MasterChef.
function claimAPE() public {
PoolInfo storage pool = poolInfo;
UserInfo storage user = userInfo[msg.sender];
updatePool();
uint256 APEReward = user.amount.mul(pool.accAPEPerShare).div(1e12).sub(user.rewardAPEDebt);
pool.lpToken.safeTransfer(msg.sender, APEReward);
pool.lastAPERewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase));
user.rewardAPEDebt = user.amount.mul(pool.accAPEPerShare).div(1e12);
}
// Safe APE transfer function to admin.
function accessAPETokens(address _to, uint256 _amount) public {
require(_to != address(0), "Invalid to address");
require(msg.sender == adminaddr, "sender must be admin address");
require(totalAPEStaked.sub(totalAPEUsedForPurchase) >= _amount, "Amount must be less than staked APE amount");
PoolInfo storage pool = poolInfo;
uint256 APEBal = pool.lpToken.balanceOf(address(this));
if (_amount > APEBal) {
pool.lpToken.safeTransfer(_to, APEBal);
totalAPEUsedForPurchase = totalAPEUsedForPurchase.add(APEBal);
} else {
pool.lpToken.safeTransfer(_to, _amount);
totalAPEUsedForPurchase = totalAPEUsedForPurchase.add(_amount);
}
emit AccessAPEToken(_to, _amount, totalAPEUsedForPurchase);
}
// Safe add APE in pool
function addAPETokensInPool(uint256 _amount) public {
require(_amount > 0, "APE amount must be greater than 0");
require(msg.sender == adminaddr, "sender must be admin address");
require(_amount.add(totalAPEStaked.sub(totalAPEUsedForPurchase)) <= totalAPEStaked, "Amount must be less than staked APE amount");
PoolInfo storage pool = poolInfo;
totalAPEUsedForPurchase = totalAPEUsedForPurchase.sub(_amount);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
emit AddAPETokensInPool(_amount, totalAPEUsedForPurchase);
}
// Update Reward per block
function updateRewardPerBlock(uint256 _newRewardPerBlock) public onlyOwner {
updatePool();
emit RewardPerBlock(VEMPPerBlock, _newRewardPerBlock);
VEMPPerBlock = _newRewardPerBlock;
}
// Update withdraw status
function updateWithdrawStatus(bool _status) public onlyOwner {
require(withdrawStatus != _status, "Already same status");
withdrawStatus = _status;
}
// Update reward end status
function updateRewardEndStatus(bool _status, uint256 _rewardEndBlock) public onlyOwner {
require(rewardEndStatus != _status, "Already same status");
rewardEndBlock = _rewardEndBlock;
rewardEndStatus = _status;
emit RewardEndStatus(_status, _rewardEndBlock);
}
// Update admin address by the previous admin.
function admin(address _adminaddr) public {
require(_adminaddr != address(0), "Invalid admin address");
require(msg.sender == adminaddr, "admin: wut?");
adminaddr = _adminaddr;
}
// Safe VEMP transfer function to admin.
function emergencyWithdrawRewardTokens(address _to, uint256 _amount) public {
require(_to != address(0), "Invalid to address");
require(msg.sender == adminaddr, "sender must be admin address");
safeVEMPTransfer(_to, _amount);
}
} | Earn APE tokens to MasterChef. | function claimAPE() public {
PoolInfo storage pool = poolInfo;
UserInfo storage user = userInfo[msg.sender];
updatePool();
uint256 APEReward = user.amount.mul(pool.accAPEPerShare).div(1e12).sub(user.rewardAPEDebt);
pool.lpToken.safeTransfer(msg.sender, APEReward);
pool.lastAPERewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalAPEStaked.sub(totalAPEUsedForPurchase));
user.rewardAPEDebt = user.amount.mul(pool.accAPEPerShare).div(1e12);
}
| 2,416,984 |
./full_match/5/0xE4B77C4738eA64922a03c7287cBA6D400f5BA349/sources/contracts/GoingUpProjects.sol | Withdraw native tokens (matic) | function withdrawFunds() public onlyAdmin {
payable(msg.sender).transfer(address(this).balance);
}
| 1,867,400 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./IPNS.sol";
contract PNS is IPNS, ERC721Enumerable {
// ownable
address private _root;
modifier onlyRoot() {
require(_root == msg.sender, "Ownable: caller is not the root");
_;
}
function transferRootOwnership(address newRoot) public virtual override onlyRoot {
require(newRoot != address(0), "Ownable: new root is the zero address");
_setRoot(newRoot);
}
function _setRoot(address newRoot) private {
address oldRoot = _root;
_root = newRoot;
emit RootOwnershipTransferred(oldRoot, _root);
}
function root() public view virtual override returns (address) {
return _root;
}
// ERC721 methods
constructor() public ERC721("PNS", "pns") {
_setRoot(msg.sender);
}
function exists(uint256 tokenId) public view virtual override returns(bool) {
return _exists(tokenId);
}
// todo : put `to` last
function mint(address to, uint256 newTokenId) public virtual override onlyRoot {
_mint(to, newTokenId);
}
function _baseURI() internal view override returns (string memory) {
return "https://meta.dot.site/";
}
modifier authorised(uint256 tokenId) {
require(_root == msg.sender || isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_;
}
function isApprovedOrOwner(address addr, uint256 tokenId) public view override returns(bool) {
return _isApprovedOrOwner(addr, tokenId);
}
// registry
mapping (uint256 => address) resolvers;
function resolver(uint256 tokenId) public virtual override view returns (address) {
return resolvers[tokenId];
}
function setResolver(uint256 tokenId, address resolver) public virtual override authorised(tokenId) {
emit NewResolver(tokenId, resolver);
resolvers[tokenId] = resolver;
}
function _mintSubnode(uint256 tokenId, bytes32 label, address to) private authorised(tokenId) returns (uint256) {
bytes32 subnode = keccak256(abi.encodePacked(tokenId, label));
uint256 subtokenId = uint256(subnode);
_mint(to, subtokenId);
return subtokenId;
}
function mintSubdomain(uint256 tokenId, string calldata name, address to) public virtual override onlyRoot returns (uint256) {
bytes32 label = keccak256(bytes(name));
uint256 subtokenId = _mintSubnode(tokenId, label, to);
emit NewSubnameOwner(tokenId, name, to);
return subtokenId;
}
function burn(uint256 tokenId) public virtual override onlyRoot {
_burn(tokenId);
}
// registrar
}
| todo : put `to` last | function mint(address to, uint256 newTokenId) public virtual override onlyRoot {
_mint(to, newTokenId);
}
| 13,101,538 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import "hardhat/console.sol";
import "@openzeppelin/contracts/governance/TimelockController.sol";
import "@openzeppelin/contracts/utils/Multicall.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IShare } from "../interfaces/IShare.sol";
import { IMembership } from "../interfaces/IMembership.sol";
import { IModule } from "../interfaces/IModule.sol";
import { DataTypes } from "../libraries/DataTypes.sol";
import { Errors } from "../libraries/Errors.sol";
import { Events } from "../libraries/Events.sol";
/**
* @title Treasury
* @notice The treasury is one of the core contracts of the DAO and is responsible for managing all of the DAO's assets,
* including external assets, eth and share tokens of the DAO.
* the treasury supports external investors in invoking the investment method to self-serve share tokens,
* and the treasury provides a hook method for modules to pull payments,
* allowing authorization for some of the assets of the modules used by the DAO.
*/
contract Treasury is TimelockController, Multicall {
using Address for address payable;
address public immutable share;
address public immutable membership;
DataTypes.ShareSplit public shareSplit;
DataTypes.InvestmentSettings public investmentSettings;
address[] private _proposers;
address[] private _executors = [address(0)];
mapping(address => uint256) private _investThresholdInERC20;
mapping(address => uint256) private _investRatioInERC20;
mapping(address => DataTypes.ModulePayment) private _modulePayments;
constructor(
uint256 timelockDelay,
address membershipTokenAddress,
address shareTokenAddress,
DataTypes.InvestmentSettings memory settings
) TimelockController(timelockDelay, _proposers, _executors) {
membership = membershipTokenAddress;
share = shareTokenAddress;
investmentSettings = settings;
_mappingSettings(settings);
}
modifier investmentEnabled() {
if (!investmentSettings.enableInvestment)
revert Errors.InvestmentDisabled();
_;
}
/**
* @dev Shortcut method
* Allows distribution of shares to members in corresponding proportions (index is tokenID)
* must be called by the timelock itself (requires a voting process)
*/
function vestingShare(uint256[] calldata tokenId, uint8[] calldata shareRatio)
public
onlyRole(TIMELOCK_ADMIN_ROLE)
{
uint256 _shareTreasury = IShare(share).balanceOf(address(this));
if (_shareTreasury == 0) revert Errors.NoShareInTreasury();
uint256 _membersShare = _shareTreasury * (shareSplit.members / 100);
if (_membersShare == 0) revert Errors.NoMembersShareToVest();
for (uint256 i = 0; i < tokenId.length; i++) {
address _member = IMembership(membership).ownerOf(tokenId[i]);
IShare(share).transfer(_member, (_membersShare * shareRatio[i]) / 100);
}
}
/**
* @dev Shortcut method
* to update settings for investment (requires a voting process)
*/
function updateInvestmentSettings(
DataTypes.InvestmentSettings memory settings
) public onlyRole(TIMELOCK_ADMIN_ROLE) {
investmentSettings = settings;
_mappingSettings(settings);
}
/**
* @dev Shortcut method
* to update share split (requires a voting process)
*/
function updateShareSplit(DataTypes.ShareSplit memory _shareSplit)
public
onlyRole(TIMELOCK_ADMIN_ROLE)
{
shareSplit = _shareSplit;
}
/**
* @dev Invest in ETH
* Allows external investors to transfer to ETH for investment.
* ETH will issue share token of DAO at a set rate
*/
function invest() external payable investmentEnabled {
if (investmentSettings.investRatioInETH == 0)
revert Errors.InvestmentDisabled();
if (msg.value < investmentSettings.investThresholdInETH)
revert Errors.InvestmentThresholdNotMet(
investmentSettings.investThresholdInETH
);
_invest(
msg.value / investmentSettings.investRatioInETH,
address(0),
msg.value
);
}
/**
* @dev Invest in ERC20 tokens
* External investors are allowed to invest in ERC20,
* which is issued as a DAO share token at a set rate.
* @notice Before calling this method, the approve method of the corresponding ERC20 contract must be called.
*/
function investInERC20(address token) external investmentEnabled {
if (_investRatioInERC20[token] == 0)
revert Errors.InvestmentInERC20Disabled(token);
uint256 _radio = _investRatioInERC20[token];
if (_radio == 0) revert Errors.InvestmentInERC20Disabled(token);
uint256 _threshold = _investThresholdInERC20[token];
uint256 _allowance = IShare(token).allowance(_msgSender(), address(this));
if (_allowance < _threshold)
revert Errors.InvestmentInERC20ThresholdNotMet(token, _threshold);
IShare(token).transferFrom(_msgSender(), address(this), _allowance);
_invest(_allowance / _radio, token, _allowance);
}
/**
* @dev Pull module payment
* The DAO module pulls the required eth and ERC20 token
* @notice Need to ensure that the number of authorizations is greater than the required number before pulling.
* this method is usually required by the module designer,
* and the method checks whether the module is mounted on the same DAO
*/
function pullModulePayment(
uint256 eth,
address[] calldata tokens,
uint256[] calldata amounts
) public {
if (tokens.length != amounts.length) revert Errors.InvalidTokenAmounts();
address moduleAddress = _msgSender();
if (IModule(moduleAddress).membership() != membership)
revert Errors.NotMember();
DataTypes.ModulePayment storage _payments = _modulePayments[moduleAddress];
address _timelock = address(IModule(moduleAddress).timelock());
address payable _target = payable(_timelock);
if (!_payments.approved) revert Errors.ModuleNotApproved();
if (eth > 0) {
if (eth > _payments.eth) revert Errors.NotEnoughETH();
_payments.eth -= eth;
_target.sendValue(eth);
}
for (uint256 i = 0; i < tokens.length; i++) {
IERC20 _token = IERC20(tokens[i]);
if (_token.allowance(address(this), _timelock) < amounts[i])
revert Errors.NotEnoughTokens();
_token.transferFrom(address(this), _timelock, amounts[i]);
_payments.erc20[tokens[i]] -= amounts[i];
}
emit Events.ModulePaymentPulled(
moduleAddress,
eth,
tokens,
amounts,
block.timestamp
);
}
/**
* @dev Approve module payment
* Authorize a module to use the corresponding eth and ERC20 token
*/
function approveModulePayment(
address moduleAddress,
uint256 eth,
address[] calldata tokens,
uint256[] calldata amounts
) public onlyRole(TIMELOCK_ADMIN_ROLE) {
if (tokens.length != amounts.length) revert Errors.InvalidTokenAmounts();
if (IModule(moduleAddress).membership() != membership)
revert Errors.NotMember();
DataTypes.ModulePayment storage _payments = _modulePayments[moduleAddress];
_payments.approved = true;
_payments.eth = eth;
for (uint256 i = 0; i < tokens.length; i++) {
IERC20 _token = IERC20(tokens[i]);
if (_token.balanceOf(address(this)) < amounts[i])
revert Errors.NotEnoughTokens();
_payments.erc20[tokens[i]] = amounts[i];
_token.approve(address(IModule(moduleAddress).timelock()), amounts[i]);
}
emit Events.ModulePaymentApproved(
moduleAddress,
eth,
tokens,
amounts,
block.timestamp
);
}
/**
* @dev Private method of realizing external investments
* The converted share token is automatically transferred to the external investor,
* and if there are not enough shares in the vault, additional shares are automatically issued.
* At the same time, the act of investing will mint a new investor status NFT membership card,
* ensuring that the investor can participate in the voting of board members (1/1 NFT Votes).
*/
function _invest(
uint256 _shareTobeClaimed,
address _token,
uint256 _amount
) private {
uint256 _shareTreasury = IShare(share).balanceOf(address(this));
if (_shareTreasury < _shareTobeClaimed) {
IShare(share).mint(address(this), _shareTobeClaimed - _shareTreasury);
}
IShare(share).transfer(_msgSender(), _shareTobeClaimed);
IMembership(membership).investMint(_msgSender());
if (_token == address(0)) {
emit Events.InvestInETH(_msgSender(), msg.value, _shareTobeClaimed);
} else {
emit Events.InvestInERC20(
_msgSender(),
_token,
_amount,
_shareTobeClaimed
);
}
}
// @dev mapping arrays to maps cause of the lack of support of params mapping in Solidity
function _mappingSettings(DataTypes.InvestmentSettings memory settings)
private
{
if (settings.investInERC20.length > 0) {
for (uint256 i = 0; i < settings.investInERC20.length; i++) {
address _token = settings.investInERC20[i];
_investThresholdInERC20[_token] = settings.investThresholdInERC20[i];
_investRatioInERC20[_token] = settings.investRatioInERC20[i];
}
}
}
}
| mapping arrays to maps cause of the lack of support of params mapping in Solidity | function _mappingSettings(DataTypes.InvestmentSettings memory settings)
private
{
if (settings.investInERC20.length > 0) {
for (uint256 i = 0; i < settings.investInERC20.length; i++) {
address _token = settings.investInERC20[i];
_investThresholdInERC20[_token] = settings.investThresholdInERC20[i];
_investRatioInERC20[_token] = settings.investRatioInERC20[i];
}
}
}
| 2,520,466 |
pragma solidity 0.6.7;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../shared/libs/LibChannelCrypto.sol";
import "./LibDispute.sol";
/// @title LibStateChannelApp
/// @author Liam Horne - <[email protected]>
/// @notice Contains the structures and enums needed when disputing apps
contract LibStateChannelApp is LibDispute {
using LibChannelCrypto for bytes32;
using SafeMath for uint256;
// A minimal structure that uniquely identifies a single instance of an App
struct AppIdentity {
address multisigAddress;
uint256 channelNonce;
address[] participants;
address appDefinition;
uint256 defaultTimeout;
}
// A structure representing the state of a CounterfactualApp instance from the POV of the blockchain
// NOTE: AppChallenge is the overall state of a channelized app instance,
// appStateHash is the hash of a state specific to the CounterfactualApp (e.g. chess position)
struct AppChallenge {
ChallengeStatus status;
bytes32 appStateHash;
uint256 versionNumber;
uint256 finalizesAt;
}
/// @dev Checks whether the given timeout has passed
/// @param timeout a timeout as block number
function hasPassed(
uint256 timeout
)
public
view
returns (bool)
{
return timeout <= block.number;
}
/// @dev Checks whether it is still possible to send all-party-signed states
/// @param appChallenge the app challenge to check
function isDisputable(
AppChallenge memory appChallenge
)
public
view
returns (bool)
{
return appChallenge.status == ChallengeStatus.NO_CHALLENGE ||
(
appChallenge.status == ChallengeStatus.IN_DISPUTE &&
!hasPassed(appChallenge.finalizesAt)
);
}
/// @dev Checks an outcome for a challenge has been set
/// @param appChallenge the app challenge to check
function isOutcomeSet(
AppChallenge memory appChallenge
)
public
pure
returns (bool)
{
return appChallenge.status == ChallengeStatus.OUTCOME_SET;
}
/// @dev Checks whether it is possible to send actions to progress state
/// @param appChallenge the app challenge to check
/// @param defaultTimeout the app instance's default timeout
function isProgressable(
AppChallenge memory appChallenge,
uint256 defaultTimeout
)
public
view
returns (bool)
{
return
(
appChallenge.status == ChallengeStatus.IN_DISPUTE &&
hasPassed(appChallenge.finalizesAt) &&
!hasPassed(appChallenge.finalizesAt.add(defaultTimeout))
) ||
(
appChallenge.status == ChallengeStatus.IN_ONCHAIN_PROGRESSION &&
!hasPassed(appChallenge.finalizesAt)
);
}
/// @dev Checks whether it is possible to cancel a given challenge
/// @param appChallenge the app challenge to check
/// @param defaultTimeout the app instance's default timeout
function isCancellable(
AppChallenge memory appChallenge,
uint256 defaultTimeout
)
public
view
returns (bool)
{
// Note: we also initially allowed cancelling a dispute during
// the dispute phase but before timeout had expired.
// TODO: does that make sense to add back in?
return isProgressable(appChallenge, defaultTimeout);
}
/// @dev Checks whether the state is finalized
/// @param appChallenge the app challenge to check
/// @param defaultTimeout the app instance's default timeout
function isFinalized(
AppChallenge memory appChallenge,
uint256 defaultTimeout
)
public
view
returns (bool)
{
return (
(
appChallenge.status == ChallengeStatus.IN_DISPUTE &&
hasPassed(appChallenge.finalizesAt.add(defaultTimeout))
) ||
(
appChallenge.status == ChallengeStatus.IN_ONCHAIN_PROGRESSION &&
hasPassed(appChallenge.finalizesAt)
) ||
(
appChallenge.status == ChallengeStatus.EXPLICITLY_FINALIZED
)
);
}
/// @dev Verifies signatures given the signer addresses
/// @param signatures message `txHash` signature
/// @param txHash operation ethereum signed message hash
/// @param signers addresses of all signers in order
function verifySignatures(
bytes[] memory signatures,
bytes32 txHash,
address[] memory signers
)
public
pure
returns (bool)
{
require(
signers.length == signatures.length,
"Signers and signatures should be of equal length"
);
for (uint256 i = 0; i < signers.length; i++) {
require(
signers[i] == txHash.verifyChannelMessage(signatures[i]),
"Invalid signature"
);
}
return true;
}
}
| Checks whether the given timeout has passed timeout a timeout as block number | function hasPassed(
uint256 timeout
)
public
view
returns (bool)
{
return timeout <= block.number;
}
| 12,943,723 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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;
}
}
/**
* @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: node_modules\@openzeppelin\contracts\math\SafeMath.sol
/**
* @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: node_modules\@openzeppelin\contracts\utils\Address.sol
/**
* @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\ERC20.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;
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_) {
_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 { }
}
// File: @openzeppelin\contracts\math\SafeMath.sol
/**
* @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\access\AccessControl.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());
}
}
}
// File: contracts\EAccessControl.sol
/**
* @title Elysia's Access Control
* @notice Control admin and whitelisted account
* @author Elysia
*/
contract EAccessControl is AccessControl {
bytes32 public constant WHITELISTED = keccak256("WHITELISTED");
/*** Admin Functions on Whitelist ***/
/**
* @notice Add an 'account' to the whitelist
* @param account The address of account to add
*/
function addAddressToWhitelist(address account) public virtual onlyAdmin {
grantRole(WHITELISTED, account);
}
function addAddressesToWhitelist(address[] memory accounts)
public
virtual
onlyAdmin
{
uint256 len = accounts.length;
for (uint256 i = 0; i < len; i++) {
grantRole(WHITELISTED, accounts[i]);
}
}
/**
* @notice remove an 'account' from the whitelist
* @param account The address of account to remove
*/
function removeAddressFromWhitelist(address account)
public
virtual
onlyAdmin
{
revokeRole(WHITELISTED, account);
}
function removeAddressesFromWhitelist(address[] memory accounts)
public
virtual
onlyAdmin
{
uint256 len = accounts.length;
for (uint256 i = 0; i < len; i++) {
revokeRole(WHITELISTED, accounts[i]);
}
}
/*** Access Controllers ***/
/// @dev Restricted to members of the whitelisted user.
modifier onlyWhitelisted() {
require(isWhitelisted(msg.sender), "Restricted to whitelisted.");
_;
}
/// @dev Restricted to members of the admin role.
modifier onlyAdmin() {
require(isAdmin(msg.sender), "Restricted to admin.");
_;
}
/// @dev Return `true` if the account belongs to whitelist.
function isWhitelisted(address account) public virtual view returns (bool) {
return hasRole(WHITELISTED, account);
}
/// @dev Return `true` if the account belongs to the admin role.
function isAdmin(address account) public virtual view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, account);
}
}
// File: contracts\PriceManager.sol
interface OraclePrice {
function getCurrentPrice() external view returns (uint256);
}
/**
* @title PriceManager
* @notice Manage elysia price and asset token price
* @author Elysia
*/
contract PriceManager is EAccessControl {
/// @notice Emitted when el Price is changed
event NewElPrice(uint256 newElPrice);
/// @notice Emitted when price is changed
event NewPrice(uint256 newPrice);
/// @notice Emitted when price contract address is changed
// event NewPriceContractAddress(address priceContractAddress);
event NewSetPriceContract(address priceContractAddress);
// USD per Elysia token
// decimals: 18
uint256 public _elPrice;
// USD per Elysia Asset Token
// decimals: 18
uint256 public _price;
OraclePrice public oracle_price;
// TODO
// Use oracle like chainlink
function getElPrice() public view returns (uint256) {
if(address(oracle_price) != address(0)) {
uint256 _elOraclePrice = oracle_price.getCurrentPrice();
return _elOraclePrice;
} else {
return _elPrice;
}
}
function getPrice() public view returns (uint256) {
return _price;
}
function setElPrice(uint256 elPrice_) external onlyAdmin returns (bool) {
_elPrice = elPrice_;
emit NewElPrice(elPrice_);
return true;
}
function setPrice(uint256 price_) external onlyAdmin returns (bool) {
_price = price_;
emit NewPrice(price_);
return true;
}
function toElAmount(uint256 amount) public view returns (uint256) {
uint256 amountEl = (amount * _price * (10**18)) / _elPrice;
require(
(amountEl / amount) == ((_price * (10**18)) / _elPrice),
"PriceManager: multiplication overflow"
);
return amountEl;
}
function setPriceContract(address priceContractAddress_) external onlyAdmin returns (bool) {
oracle_price = OraclePrice(priceContractAddress_);
emit NewSetPriceContract(priceContractAddress_);
return true;
}
function getOracleContract() external view returns (address) {
return address(oracle_price);
}
}
contract EErc20 is Context, IERC20 {
using SafeMath for uint256;
mapping(address => uint256) public _balances;
mapping(address => mapping(address => uint256)) public _allowances;
uint256 public _totalSupply;
string public _name;
string public _symbol;
uint8 public _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. 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 override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public override 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
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
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
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 {}
}
// File: contracts\RewardManager.sol
/**
* @title RewardManager
* @notice Manage rewards by _refToken and block numbers
* @author Elysia
*/
contract RewardManager is EAccessControl {
/// @notice Emitted when rewards per block is changed
event NewRewardPerBlock(uint256 newRewardPerBlock);
EErc20 public _refToken; // reftoken should be initialized by EAssetToken
// monthlyRent$/(secondsPerMonth*averageBlockPerSecond)
// Decimals: 18
uint256 public _rewardPerBlock;
// Account rewards (USD)
// Decimals: 18
mapping(address => uint256) private _rewards;
// Account block numbers
mapping(address => uint256) private _blockNumbers;
function getRewardPerBlock() public view returns (uint256) {
return _rewardPerBlock;
}
function setRewardPerBlock(uint256 rewardPerBlock_)
external
onlyAdmin
returns (bool)
{
_rewardPerBlock = rewardPerBlock_;
emit NewRewardPerBlock(rewardPerBlock_);
return true;
}
/*** Reward functions ***/
/**
* @notice Get reward
* @param account Addresss
* @return saved reward + new reward
*/
function getReward(address account) public view returns (uint256) {
uint256 newReward = 0;
if (
_blockNumbers[account] != 0 && block.number > _blockNumbers[account]
) {
newReward =
(_refToken.balanceOf(account) *
(block.number - _blockNumbers[account]) *
_rewardPerBlock) /
_refToken.totalSupply();
}
return newReward + _rewards[account];
}
function _saveReward(address account) internal returns (bool) {
if (account == address(this)) {
return true;
}
_rewards[account] = getReward(account);
_blockNumbers[account] = block.number;
return true;
}
function _clearReward(address account) internal returns (bool) {
_rewards[account] = 0;
_blockNumbers[account] = block.number;
return true;
}
}
// File: contracts\AssetToken.sol
/**
* @title Elysia's AssetToken
* @author Elysia
*/
contract AssetToken is EErc20, PriceManager, RewardManager {
using SafeMath for uint256;
ERC20 private _el;
uint256 public _latitude;
uint256 public _longitude;
uint256 public _assetPrice;
uint256 public _interestRate;
/// @notice Emitted when an user claimed reward
event RewardClaimed(address account, uint256 reward);
constructor(
ERC20 el_,
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 amount_,
address admin_,
uint256 elPrice_,
uint256 price_,
uint256 rewardPerBlock_,
uint256 latitude_,
uint256 longitude_,
uint256 assetPrice_,
uint256 interestRate_
){
_el = el_;
_name = name_;
_symbol = symbol_;
_decimals = decimals_;
_elPrice = elPrice_;
_price = price_;
_rewardPerBlock = rewardPerBlock_;
_latitude = latitude_;
_longitude = longitude_;
_assetPrice = assetPrice_;
_interestRate = interestRate_;
_mint(address(this), amount_);
_setupRole(DEFAULT_ADMIN_ROLE, admin_);
_setRoleAdmin(WHITELISTED, DEFAULT_ADMIN_ROLE);
_refToken = this;
}
/**
* @dev purchase asset token with el.
*
* This can be used to purchase asset token with Elysia Token (EL).
*
* Requirements:
* - `amount` this contract should have more asset token than the amount.
* - `amount` msg.sender should have more el than elAmount converted from the amount.
*/
function purchase(uint256 amount) public returns (bool) {
_checkBalance(msg.sender, address(this), amount);
require(_el.transferFrom(msg.sender, address(this), toElAmount(amount)), 'EL : transferFrom failed');
_transfer(address(this), msg.sender, amount);
return true;
}
/**
* @dev retund asset token.
*
* This can be used to refund asset token with Elysia Token (EL).
*
* Requirements:
* - `amount` msg.sender should have more asset token than the amount.
* - `amount` this contract should have more el than elAmount converted from the amount.
*/
function refund(uint256 amount) public returns (bool) {
_checkBalance(address(this), msg.sender, amount);
require(_el.transfer(msg.sender, toElAmount(amount)), 'EL : transfer failed');
_transfer(msg.sender, address(this), amount);
return true;
}
/**
* @dev check if buyer and seller have sufficient balance.
*
* This can be used to check balance of buyer and seller before swap.
*
* Requirements:
* - `amount` buyer should have more asset token than the amount.
* - `amount` seller should have more el than elAmount converted from the amount.
*/
function _checkBalance(address buyer, address seller, uint256 amount) internal {
require(_el.balanceOf(buyer) > toElAmount(amount), 'AssetToken: Insufficient buyer el balance.');
require(balanceOf(seller) > amount, 'AssetToken: Insufficient seller balance.');
}
/**
* @dev Claim account reward.
*
* This can be used to claim account accumulated rewrard with Elysia Token (EL).
*
* Emits a {RewardClaimed} event.
*
* Requirements:
* - `elPrice` cannot be the zero.
*/
function claimReward() external onlyWhitelisted {
uint256 reward = getReward(msg.sender) * 10 ** 18 / _elPrice;
require(reward < _el.balanceOf(address(this)), 'AssetToken: Insufficient seller balance.');
_el.transfer(msg.sender, reward);
_clearReward(msg.sender);
emit RewardClaimed(msg.sender, reward);
}
/**
* @dev 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 override(EErc20) {
require(sender != address(0), "AssetToken: transfer from the zero address");
require(recipient != address(0), "AssetToken: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
require(_balances[sender] >= amount, "AssetToken: transfer amount exceeds balance");
/* RewardManager */
_saveReward(sender);
_saveReward(recipient);
_balances[sender] = _balances[sender] - amount;
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Withdraw all El from this contract to admin
*/
function withdrawElToAdmin() public onlyAdmin {
_el.transfer(msg.sender, _el.balanceOf(address(this)));
}
} | Withdraw all El from this contract to admin/ | function withdrawElToAdmin() public onlyAdmin {
_el.transfer(msg.sender, _el.balanceOf(address(this)));
}
| 14,490,687 |
./partial_match/42220/0x00e533B7d6255D05b7f15034B1c989c21F51b91C/sources/project:/contracts/utils/BuyGDClone.sol | Calculates the minimum amount of tokens that can be received for a given amount of base tokens, based on the time-weighted average price (TWAP) of the token pair over a specified period of time. baseAmount The amount of base tokens to swap. baseToken The address of the base token. return minTwap The minimum amount of G$ expected to receive by twap/ | function minAmountByTWAP(
uint256 baseAmount,
address baseToken,
uint32 period
) public view returns (uint256 minTwap, uint256 quote) {
uint128 toConvert = uint128(baseAmount);
if (baseToken == celo) {
(quote, ) = oracle.quoteAllAvailablePoolsWithTimePeriod(
toConvert,
baseToken,
cusd,
period
);
toConvert = uint128(quote);
}
(quote, ) = oracle.quoteAllAvailablePoolsWithTimePeriod(
toConvert,
cusd,
gd,
period
);
}
| 3,494,629 |
./full_match/100/0xB4d0774C38bD9A4539CA7810ddEd8C3599a766Fe/sources/contracts/rari-fuse/src/FuseFeeDistributor.sol | Sets the proportion of Fuse pool interest taken as a protocol fee. _minBorrowEth Minimum borrow balance (in ETH) per user per Fuse pool asset (only checked on new borrows, not redemptions). _maxSupplyEth Maximum supply balance (in ETH) per user per Fuse pool asset. _maxUtilizationRate Maximum utilization rate (scaled by 1e18) for Fuse pool assets (only checked on new borrows, not redemptions)./ | function _setPoolLimits(
uint256 _minBorrowEth,
uint256 _maxSupplyEth,
uint256 _maxUtilizationRate
) external onlyOwner {
minBorrowEth = _minBorrowEth;
maxSupplyEth = _maxSupplyEth;
maxUtilizationRate = _maxUtilizationRate;
}
| 14,288,703 |
pragma solidity ^0.4.25;
import './AppDD.sol';
/**
* @title External interface for AppDAO
*/
interface CommonI {
function transferOwnership(address _newOwner) external;
function acceptOwnership() external;
function updateAgent(address _agent, bool _state) external;
}
/**
* @title Decentralized Autonomous Organization for Application
*/
contract AppDAO is AppDD {
//minimum balance for adding proposal - default 100 tokens
uint minBalance = 10000000000;
// minimum quorum - number of votes must be more than minimum quorum
uint public minimumQuorum;
// debating period duration
uint public debatingPeriodDuration;
// requisite majority of votes (by the system a simple majority)
uint public requisiteMajority;
struct _Proposal {
// proposal may execute only after voting ended
uint endTimeOfVoting;
// if executed = true
bool executed;
// if passed = true
bool proposalPassed;
// number of votes already voted
uint numberOfVotes;
// in support of votes
uint votesSupport;
// against votes
uint votesAgainst;
// the address where the `amount` will go to if the proposal is accepted
address recipient;
// the amount to transfer to `recipient` if the proposal is accepted.
uint amount;
// keccak256(abi.encodePacked(recipient, amount, transactionByteCode));
bytes32 transactionHash;
// a plain text description of the proposal
string desc;
// a hash of full description data of the proposal (optional)
string fullDescHash;
}
_Proposal[] public Proposals;
event ProposalAdded(uint proposalID, address recipient, uint amount, string description, string fullDescHash);
event Voted(uint proposalID, bool position, address voter, string justification);
event ProposalTallied(uint proposalID, uint votesSupport, uint votesAgainst, uint quorum, bool active);
event ChangeOfRules(uint newMinimumQuorum, uint newdebatingPeriodDuration, uint newRequisiteMajority);
event Payment(address indexed sender, uint amount);
// Modifier that allows only owners of Application tokens to vote and create new proposals
modifier onlyMembers {
require(balances[msg.sender] > 0);
_;
}
/**
* Change voting rules
*
* Make so that Proposals need to be discussed for at least `_debatingPeriodDuration/60` hours,
* have at least `_minimumQuorum` votes, and have 50% + `_requisiteMajority` votes to be executed
*
* @param _minimumQuorum how many members must vote on a proposal for it to be executed
* @param _debatingPeriodDuration the minimum amount of delay between when a proposal is made and when it can be executed
* @param _requisiteMajority the proposal needs to have 50% plus this number
*/
function changeVotingRules(
uint _minimumQuorum,
uint _debatingPeriodDuration,
uint _requisiteMajority
) onlyOwner public {
minimumQuorum = _minimumQuorum;
debatingPeriodDuration = _debatingPeriodDuration;
requisiteMajority = _requisiteMajority;
emit ChangeOfRules(minimumQuorum, debatingPeriodDuration, requisiteMajority);
}
/**
* Add Proposal
*
* Propose to send `_amount / 1e18` ether to `_recipient` for `_desc`. `_transactionByteCode ? Contains : Does not contain` code.
*
* @param _recipient who to send the ether to
* @param _amount amount of ether to send, in wei
* @param _desc Description of job
* @param _fullDescHash Hash of full description of job
* @param _transactionByteCode bytecode of transaction
*/
function addProposal(address _recipient, uint _amount, string _desc, string _fullDescHash, bytes _transactionByteCode, uint _debatingPeriodDuration) onlyMembers public returns (uint) {
require(balances[msg.sender] > minBalance);
if (_debatingPeriodDuration == 0) {
_debatingPeriodDuration = debatingPeriodDuration;
}
Proposals.push(_Proposal({
endTimeOfVoting: now + _debatingPeriodDuration * 1 minutes,
executed: false,
proposalPassed: false,
numberOfVotes: 0,
votesSupport: 0,
votesAgainst: 0,
recipient: _recipient,
amount: _amount,
transactionHash: keccak256(abi.encodePacked(_recipient, _amount, _transactionByteCode)),
desc: _desc,
fullDescHash: _fullDescHash
}));
// add proposal in ERC20 base contract for block transfer
super.addProposal(Proposals.length-1, Proposals[Proposals.length-1].endTimeOfVoting);
emit ProposalAdded(Proposals.length-1, _recipient, _amount, _desc, _fullDescHash);
return Proposals.length-1;
}
/**
* Check if a proposal code matches
*
* @param _proposalID number of the proposal to query
* @param _recipient who to send the ether to
* @param _amount amount of ether to send
* @param _transactionByteCode bytecode of transaction
*/
function checkProposalCode(uint _proposalID, address _recipient, uint _amount, bytes _transactionByteCode) view public returns (bool) {
require(Proposals[_proposalID].recipient == _recipient);
require(Proposals[_proposalID].amount == _amount);
// compare ByteCode
return Proposals[_proposalID].transactionHash == keccak256(abi.encodePacked(_recipient, _amount, _transactionByteCode));
}
/**
* Log a vote for a proposal
*
* Vote `supportsProposal? in support of : against` proposal #`proposalID`
*
* @param _proposalID number of proposal
* @param _supportsProposal either in favor or against it
* @param _justificationText optional justification text
*/
function vote(uint _proposalID, bool _supportsProposal, string _justificationText) onlyMembers public returns (uint) {
// Get the proposal
_Proposal storage p = Proposals[_proposalID];
require(now <= p.endTimeOfVoting);
// get numbers of votes for msg.sender
uint votes = safeSub(balances[msg.sender], voted[_proposalID][msg.sender]);
require(votes > 0);
voted[_proposalID][msg.sender] = safeAdd(voted[_proposalID][msg.sender], votes);
// Increase the number of votes
p.numberOfVotes = p.numberOfVotes + votes;
if (_supportsProposal) {
p.votesSupport = p.votesSupport + votes;
} else {
p.votesAgainst = p.votesAgainst + votes;
}
emit Voted(_proposalID, _supportsProposal, msg.sender, _justificationText);
return p.numberOfVotes;
}
/**
* Finish vote
*
* Count the votes proposal #`_proposalID` and execute it if approved
*
* @param _proposalID proposal number
* @param _transactionByteCode optional: if the transaction contained a bytecode, you need to send it
*/
function executeProposal(uint _proposalID, bytes _transactionByteCode) public {
// Get the proposal
_Proposal storage p = Proposals[_proposalID];
require(now > p.endTimeOfVoting // If it is past the voting deadline
&& !p.executed // and it has not already been executed
&& p.transactionHash == keccak256(abi.encodePacked(p.recipient, p.amount, _transactionByteCode)) // and the supplied code matches the proposal
&& p.numberOfVotes >= minimumQuorum); // and a minimum quorum has been reached
// then execute result
if (p.votesSupport > requisiteMajority) {
// Proposal passed; execute the transaction
require(p.recipient.call.value(p.amount)(_transactionByteCode));
p.proposalPassed = true;
} else {
// Proposal failed
p.proposalPassed = false;
}
p.executed = true;
// delete proposal from active list
super.delProposal(_proposalID);
// Fire Events
emit ProposalTallied(_proposalID, p.votesSupport, p.votesAgainst, p.numberOfVotes, p.proposalPassed);
}
// function is needed if execution transactionByteCode in Proposal failed
function delActiveProposal(uint _proposalID) public onlyOwner {
// delete proposal from active list
super.delProposal(_proposalID);
}
/**
* @dev Allows the DAO to transfer control of the _contract to a _newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _contract, address _newOwner) public onlyOwner {
CommonI(_contract).transferOwnership(_newOwner);
}
/**
* @dev Accept transferOwnership on a this (DAO) contract
*/
function acceptOwnership(address _contract) public onlyOwner {
CommonI(_contract).acceptOwnership();
}
function updateAgent(address _contract, address _agent, bool _state) public onlyOwner {
CommonI(_contract).updateAgent(_agent, _state);
}
/**
* Set minimum balance for adding proposal
*/
function setMinBalance(uint _minBalance) public onlyOwner {
assert(_minBalance > 0);
minBalance = _minBalance;
}
} | Change voting rules Make so that Proposals need to be discussed for at least `_debatingPeriodDuration/60` hours, have at least `_minimumQuorum` votes, and have 50% + `_requisiteMajority` votes to be executed _minimumQuorum how many members must vote on a proposal for it to be executed _debatingPeriodDuration the minimum amount of delay between when a proposal is made and when it can be executed _requisiteMajority the proposal needs to have 50% plus this number/ | function changeVotingRules(
uint _minimumQuorum,
uint _debatingPeriodDuration,
uint _requisiteMajority
) onlyOwner public {
minimumQuorum = _minimumQuorum;
debatingPeriodDuration = _debatingPeriodDuration;
requisiteMajority = _requisiteMajority;
emit ChangeOfRules(minimumQuorum, debatingPeriodDuration, requisiteMajority);
}
| 2,555,635 |
./partial_match/80001/0x69fcF6A264F5017CBdA314535ddD5c765A7F5968/sources/contracts/AlgebraPool.sol | @inheritdoc IAlgebraPoolActions | function initialize(uint160 initialPrice) external override {
globalState.price = initialPrice;
if (plugin != address(0)) {
IAlgebraPlugin(plugin).beforeInitialize(msg.sender, initialPrice).shouldReturn(IAlgebraPlugin.beforeInitialize.selector);
}
(uint16 _communityFee, int24 _tickSpacing, uint16 _fee) = _getDefaultConfiguration();
tickSpacing = _tickSpacing;
uint8 pluginConfig = globalState.pluginConfig;
globalState.tick = tick;
globalState.lastFee = _fee;
globalState.communityFee = _communityFee;
emit Initialize(initialPrice, tick);
emit TickSpacing(_tickSpacing);
emit CommunityFee(_communityFee);
if (pluginConfig.hasFlag(Plugins.AFTER_INIT_FLAG)) {
IAlgebraPlugin(plugin).afterInitialize(msg.sender, initialPrice, tick).shouldReturn(IAlgebraPlugin.afterInitialize.selector);
}
}
| 8,812,783 |
./full_match/43114/0xa72f9D358c96f01C77654F927Afb7A4c7d2b95FC/sources/VictusChef.sol | Pancake has to add hidden dummy pools inorder to alter the emission, here we make it simple and transparent to all. | function updateEmissionRate(uint256 _victPerSec) external onlyOwner {
massUpdatePools();
victPerSec = _victPerSec;
emit UpdateEmissionRate(msg.sender, _victPerSec);
}
| 4,533,598 |
./full_match/97/0xef5a6C4C5411D3cc3680b10A71afb235c8aF127b/sources/project_/contracts/factory.sol | Returns beacon address to which proxy address's point to./ | function escrowBeaconAddress() public view returns (address) {
return beacon;
}
| 3,273,651 |
./full_match/80001/0x9e931a143eC263C2eF9302ca6D859F80751f6941/sources/contracts/upgradeable/WheelcoinPausable.sol | solhint-disable-next-line func-name-mixedcase, private-vars-leading-underscore | function __WheelcoinPausable_init() internal onlyInitializing {
WheelcoinRoles.__WheelcoinRoles_init();
PausableUpgradeable.__Pausable_init();
__WheelcoinPausable_init_unchained();
}
| 5,641,133 |
./full_match/42/0xC527910E9DB5bE5f18DF2EC0c77e2760908eB5E0/sources/contracts/FundMe.sol | Function to transfer Ether from this contract to address from input | function transfer(address payable _to, uint _ethAmount) payable public {
addressToAmountFunded[_to] = addressToAmountFunded[_to] + _ethAmount;
}
| 16,275,967 |
./full_match/43114/0x1959be52241f53504eE53bDaf38D436C9EadA520/sources/contracts/xUSDTFlood.sol | generate the uniswap pair path of token -> wAVAX make the swap | function swapTokensForAVAX(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WAVAX();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForAVAXSupportingFeeOnTransferTokens(
tokenAmount,
path,
block.timestamp
);
emit SwapTokensForAVAX(tokenAmount, path);
}
| 4,543,165 |
pragma solidity ^0.4.24;
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* 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);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @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
);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @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;
}
}
// File: openzeppelin-solidity/contracts/ownership/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 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;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* 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 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
// File: contracts/crowdsale/Crowdsale.sol
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/
contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for ERC20;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
// Amount tokens Sold
uint256 public tokensSold;
/**
* 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
);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
constructor(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
_preValidatePurchase(_beneficiary, weiAmount, tokens);
// update state
weiRaised = weiRaised.add(weiAmount);
tokensSold = tokensSold.add(tokens);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, weiAmount, tokens);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount, tokens);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(_beneficiary, _weiAmount);
* require(weiRaised.add(_weiAmount) <= cap);
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
* @param _tokenAmount Value in token involved in the purchase
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount,
uint256 _tokenAmount
)
internal
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
* @param _tokenAmount Value in token involved in the purchase
*/
function _postValidatePurchase(
address _beneficiary,
uint256 _weiAmount,
uint256 _tokenAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.safeTransfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
* @param _tokenAmount Value in token involved in the purchase
*/
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount,
uint256 _tokenAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
// File: contracts/crowdsale/validation/TimedCrowdsale.sol
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
// solium-disable-next-line security/no-block-members
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
constructor(uint256 _openingTime, uint256 _closingTime) public {
// solium-disable-next-line security/no-block-members
require(_openingTime >= block.timestamp);
require(_closingTime > _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
* @param _tokenAmount Amount of token purchased
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount,
uint256 _tokenAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(_beneficiary, _weiAmount, _tokenAmount);
}
}
// File: contracts/crowdsale/validation/MilestoneCrowdsale.sol
/**
* @title MilestoneCrowdsale
* @dev Crowdsale with multiple milestones separated by time and cap
* @author Nikola Wyatt <[email protected]>
*/
contract MilestoneCrowdsale is TimedCrowdsale {
using SafeMath for uint256;
uint256 public constant MAX_MILESTONE = 10;
/**
* Define pricing schedule using milestones.
*/
struct Milestone {
// Milestone index in array
uint256 index;
// UNIX timestamp when this milestone starts
uint256 startTime;
// Amount of tokens sold in milestone
uint256 tokensSold;
// Maximum amount of Tokens accepted in the current Milestone.
uint256 cap;
// How many tokens per wei you will get after this milestone has been passed
uint256 rate;
}
/**
* Store milestones in a fixed array, so that it can be seen in a blockchain explorer
* Milestone 0 is always (0, 0)
* (TODO: change this when we confirm dynamic arrays are explorable)
*/
Milestone[10] public milestones;
// How many active milestones have been created
uint256 public milestoneCount = 0;
bool public milestoningFinished = false;
constructor(
uint256 _openingTime,
uint256 _closingTime
)
TimedCrowdsale(_openingTime, _closingTime)
public
{
}
/**
* @dev Contruction, setting a list of milestones
* @param _milestoneStartTime uint[] milestones start time
* @param _milestoneCap uint[] milestones cap
* @param _milestoneRate uint[] milestones price
*/
function setMilestonesList(uint256[] _milestoneStartTime, uint256[] _milestoneCap, uint256[] _milestoneRate) public {
// Need to have tuples, length check
require(!milestoningFinished);
require(_milestoneStartTime.length > 0);
require(_milestoneStartTime.length == _milestoneCap.length && _milestoneCap.length == _milestoneRate.length);
require(_milestoneStartTime[0] == openingTime);
require(_milestoneStartTime[_milestoneStartTime.length-1] < closingTime);
for (uint iterator = 0; iterator < _milestoneStartTime.length; iterator++) {
if (iterator > 0) {
assert(_milestoneStartTime[iterator] > milestones[iterator-1].startTime);
}
milestones[iterator] = Milestone({
index: iterator,
startTime: _milestoneStartTime[iterator],
tokensSold: 0,
cap: _milestoneCap[iterator],
rate: _milestoneRate[iterator]
});
milestoneCount++;
}
milestoningFinished = true;
}
/**
* @dev Iterate through milestones. You reach end of milestones when rate = 0
* @return tuple (time, rate)
*/
function getMilestoneTimeAndRate(uint256 n) public view returns (uint256, uint256) {
return (milestones[n].startTime, milestones[n].rate);
}
/**
* @dev Checks whether the cap of a milestone has been reached.
* @return Whether the cap was reached
*/
function capReached(uint256 n) public view returns (bool) {
return milestones[n].tokensSold >= milestones[n].cap;
}
/**
* @dev Checks amount of tokens sold in milestone.
* @return Amount of tokens sold in milestone
*/
function getTokensSold(uint256 n) public view returns (uint256) {
return milestones[n].tokensSold;
}
function getFirstMilestone() private view returns (Milestone) {
return milestones[0];
}
function getLastMilestone() private view returns (Milestone) {
return milestones[milestoneCount-1];
}
function getFirstMilestoneStartsAt() public view returns (uint256) {
return getFirstMilestone().startTime;
}
function getLastMilestoneStartsAt() public view returns (uint256) {
return getLastMilestone().startTime;
}
/**
* @dev Get the current milestone or bail out if we are not in the milestone periods.
* @return {[type]} [description]
*/
function getCurrentMilestoneIndex() internal view onlyWhileOpen returns (uint256) {
uint256 index;
// Found the current milestone by evaluating time.
// If (now < next start) the current milestone is the previous
// Stops loop if finds current
for(uint i = 0; i < milestoneCount; i++) {
index = i;
// solium-disable-next-line security/no-block-members
if(block.timestamp < milestones[i].startTime) {
index = i - 1;
break;
}
}
// For the next code, you may ask why not assert if last milestone surpass cap...
// Because if its last and it is capped we would like to finish not sell any more tokens
// Check if the current milestone has reached it's cap
if (milestones[index].tokensSold > milestones[index].cap) {
index = index + 1;
}
return index;
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap from the currentMilestone.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
* @param _tokenAmount Amount of token purchased
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount,
uint256 _tokenAmount
)
internal
{
super._preValidatePurchase(_beneficiary, _weiAmount, _tokenAmount);
require(milestones[getCurrentMilestoneIndex()].tokensSold.add(_tokenAmount) <= milestones[getCurrentMilestoneIndex()].cap);
}
/**
* @dev Extend parent behavior to update current milestone state and index
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
* @param _tokenAmount Amount of token purchased
*/
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount,
uint256 _tokenAmount
)
internal
{
super._updatePurchasingState(_beneficiary, _weiAmount, _tokenAmount);
milestones[getCurrentMilestoneIndex()].tokensSold = milestones[getCurrentMilestoneIndex()].tokensSold.add(_tokenAmount);
}
/**
* @dev Get the current price.
* @return The current price or 0 if we are outside milestone period
*/
function getCurrentRate() internal view returns (uint result) {
return milestones[getCurrentMilestoneIndex()].rate;
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(getCurrentRate());
}
}
// File: contracts/price/USDPrice.sol
/**
* @title USDPrice
* @dev Contract that calculates the price of tokens in USD cents.
* Note that this contracts needs to be updated
*/
contract USDPrice is Ownable {
using SafeMath for uint256;
// PRICE of 1 ETHER in USD in cents
// So, if price is: $271.90, the value in variable will be: 27190
uint256 public ETHUSD;
// Time of Last Updated Price
uint256 public updatedTime;
// Historic price of ETH in USD in cents
mapping (uint256 => uint256) public priceHistory;
event PriceUpdated(uint256 price);
constructor() public {
}
function getHistoricPrice(uint256 time) public view returns (uint256) {
return priceHistory[time];
}
function updatePrice(uint256 price) public onlyOwner {
require(price > 0);
priceHistory[updatedTime] = ETHUSD;
ETHUSD = price;
// solium-disable-next-line security/no-block-members
updatedTime = block.timestamp;
emit PriceUpdated(ETHUSD);
}
/**
* @dev Override to extend the way in which ether is converted to USD.
* @param _weiAmount Value in wei to be converted into tokens
* @return The value of wei amount in USD cents
*/
function getPrice(uint256 _weiAmount)
public view returns (uint256)
{
return _weiAmount.mul(ETHUSD);
}
}
// File: contracts/Sale.sol
interface MintableERC20 {
function mint(address _to, uint256 _amount) public returns (bool);
}
/**
* @title PreSale
* @dev Crowdsale accepting contributions only within a time frame,
* having milestones defined, the price is defined in USD
* having a mechanism to refund sales if soft cap not capReached();
*/
contract PreSale is Ownable, Crowdsale, MilestoneCrowdsale {
using SafeMath for uint256;
/// Max amount of tokens to be contributed
uint256 public cap;
/// Minimum amount of wei per contribution
uint256 public minimumContribution;
bool public isFinalized = false;
USDPrice private usdPrice;
event Finalized();
constructor(
uint256 _rate,
address _wallet,
ERC20 _token,
uint256 _openingTime,
uint256 _closingTime,
uint256 _cap,
uint256 _minimumContribution,
USDPrice _usdPrice
)
Crowdsale(_rate, _wallet, _token)
MilestoneCrowdsale(_openingTime, _closingTime)
public
{
require(_cap > 0);
require(_minimumContribution > 0);
cap = _cap;
minimumContribution = _minimumContribution;
usdPrice = _usdPrice;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return tokensSold >= cap;
}
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() public onlyOwner {
require(!isFinalized);
require(hasClosed());
emit Finalized();
isFinalized = true;
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return usdPrice.getPrice(_weiAmount).div(getCurrentRate());
}
/**
* @dev Extend parent behavior sending heartbeat to token.
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
* @param _tokenAmount Value in token involved in the purchase
*/
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount,
uint256 _tokenAmount
)
internal
{
super._updatePurchasingState(_beneficiary, _weiAmount, _tokenAmount);
}
/**
* @dev Overrides delivery by minting tokens upon purchase. - MINTED Crowdsale
* @param _beneficiary Token purchaser
* @param _tokenAmount Number of tokens to be minted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
// Potentially dangerous assumption about the type of the token.
require(MintableERC20(address(token)).mint(_beneficiary, _tokenAmount));
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
* @param _tokenAmount Amount of token purchased
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount,
uint256 _tokenAmount
)
internal
{
super._preValidatePurchase(_beneficiary, _weiAmount, _tokenAmount);
require(_weiAmount >= minimumContribution);
require(tokensSold.add(_tokenAmount) <= cap);
}
} | Checks whether the cap has been reached. return Whether the cap was reached/ | function capReached() public view returns (bool) {
return tokensSold >= cap;
}
| 2,567,013 |
// 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/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/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/MinterRole.sol
pragma solidity ^0.5.0;
contract MinterRole is Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(_msgSender());
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Mintable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole},
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
}
// File: contracts/src/common/libs/Decimals.sol
pragma solidity 0.5.17;
/**
* Library for emulating calculations involving decimals.
*/
library Decimals {
using SafeMath for uint256;
uint120 private constant basisValue = 1000000000000000000;
/**
* Returns the ratio of the first argument to the second argument.
*/
function outOf(uint256 _a, uint256 _b)
internal
pure
returns (uint256 result)
{
if (_a == 0) {
return 0;
}
uint256 a = _a.mul(basisValue);
if (a < _b) {
return 0;
}
return (a.div(_b));
}
/**
* Returns multiplied the number by 10^18.
* This is used when there is a very large difference between the two numbers passed to the `outOf` function.
*/
function mulBasis(uint256 _a) internal pure returns (uint256) {
return _a.mul(basisValue);
}
/**
* Returns by changing the numerical value being emulated to the original number of digits.
*/
function divBasis(uint256 _a) internal pure returns (uint256) {
return _a.div(basisValue);
}
}
// File: contracts/src/common/lifecycle/Killable.sol
pragma solidity 0.5.17;
/**
* A module that allows contracts to self-destruct.
*/
contract Killable {
address payable public _owner;
/**
* Initialized with the deployer as the owner.
*/
constructor() internal {
_owner = msg.sender;
}
/**
* Self-destruct the contract.
* This function can only be executed by the owner.
*/
function kill() public {
require(msg.sender == _owner, "only owner method");
selfdestruct(_owner);
}
}
// 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: contracts/src/common/interface/IGroup.sol
pragma solidity 0.5.17;
contract IGroup {
function isGroup(address _addr) public view returns (bool);
function addGroup(address _addr) external;
function getGroupKey(address _addr) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("_group", _addr));
}
}
// File: contracts/src/common/validate/AddressValidator.sol
pragma solidity 0.5.17;
/**
* A module that provides common validations patterns.
*/
contract AddressValidator {
string constant errorMessage = "this is illegal address";
/**
* Validates passed address is not a zero address.
*/
function validateIllegalAddress(address _addr) external pure {
require(_addr != address(0), errorMessage);
}
/**
* Validates passed address is included in an address set.
*/
function validateGroup(address _addr, address _groupAddr) external view {
require(IGroup(_groupAddr).isGroup(_addr), errorMessage);
}
/**
* Validates passed address is included in two address sets.
*/
function validateGroups(
address _addr,
address _groupAddr1,
address _groupAddr2
) external view {
if (IGroup(_groupAddr1).isGroup(_addr)) {
return;
}
require(IGroup(_groupAddr2).isGroup(_addr), errorMessage);
}
/**
* Validates that the address of the first argument is equal to the address of the second argument.
*/
function validateAddress(address _addr, address _target) external pure {
require(_addr == _target, errorMessage);
}
/**
* Validates passed address equals to the two addresses.
*/
function validateAddresses(
address _addr,
address _target1,
address _target2
) external pure {
if (_addr == _target1) {
return;
}
require(_addr == _target2, errorMessage);
}
/**
* Validates passed address equals to the three addresses.
*/
function validate3Addresses(
address _addr,
address _target1,
address _target2,
address _target3
) external pure {
if (_addr == _target1) {
return;
}
if (_addr == _target2) {
return;
}
require(_addr == _target3, errorMessage);
}
}
// File: contracts/src/common/validate/UsingValidator.sol
pragma solidity 0.5.17;
// prettier-ignore
/**
* Module for contrast handling AddressValidator.
*/
contract UsingValidator {
AddressValidator private _validator;
/**
* Create a new AddressValidator contract when initialize.
*/
constructor() public {
_validator = new AddressValidator();
}
/**
* Returns the set AddressValidator address.
*/
function addressValidator() internal view returns (AddressValidator) {
return _validator;
}
}
// File: contracts/src/common/config/AddressConfig.sol
pragma solidity 0.5.17;
/**
* A registry contract to hold the latest contract addresses.
* Dev Protocol will be upgradeable by this contract.
*/
contract AddressConfig is Ownable, UsingValidator, Killable {
address public token = 0x98626E2C9231f03504273d55f397409deFD4a093;
address public allocator;
address public allocatorStorage;
address public withdraw;
address public withdrawStorage;
address public marketFactory;
address public marketGroup;
address public propertyFactory;
address public propertyGroup;
address public metricsGroup;
address public metricsFactory;
address public policy;
address public policyFactory;
address public policySet;
address public policyGroup;
address public lockup;
address public lockupStorage;
address public voteTimes;
address public voteTimesStorage;
address public voteCounter;
address public voteCounterStorage;
/**
* Set the latest Allocator contract address.
* Only the owner can execute this function.
*/
function setAllocator(address _addr) external onlyOwner {
allocator = _addr;
}
/**
* Set the latest AllocatorStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the AllocatorStorage contract is not used.
*/
function setAllocatorStorage(address _addr) external onlyOwner {
allocatorStorage = _addr;
}
/**
* Set the latest Withdraw contract address.
* Only the owner can execute this function.
*/
function setWithdraw(address _addr) external onlyOwner {
withdraw = _addr;
}
/**
* Set the latest WithdrawStorage contract address.
* Only the owner can execute this function.
*/
function setWithdrawStorage(address _addr) external onlyOwner {
withdrawStorage = _addr;
}
/**
* Set the latest MarketFactory contract address.
* Only the owner can execute this function.
*/
function setMarketFactory(address _addr) external onlyOwner {
marketFactory = _addr;
}
/**
* Set the latest MarketGroup contract address.
* Only the owner can execute this function.
*/
function setMarketGroup(address _addr) external onlyOwner {
marketGroup = _addr;
}
/**
* Set the latest PropertyFactory contract address.
* Only the owner can execute this function.
*/
function setPropertyFactory(address _addr) external onlyOwner {
propertyFactory = _addr;
}
/**
* Set the latest PropertyGroup contract address.
* Only the owner can execute this function.
*/
function setPropertyGroup(address _addr) external onlyOwner {
propertyGroup = _addr;
}
/**
* Set the latest MetricsFactory contract address.
* Only the owner can execute this function.
*/
function setMetricsFactory(address _addr) external onlyOwner {
metricsFactory = _addr;
}
/**
* Set the latest MetricsGroup contract address.
* Only the owner can execute this function.
*/
function setMetricsGroup(address _addr) external onlyOwner {
metricsGroup = _addr;
}
/**
* Set the latest PolicyFactory contract address.
* Only the owner can execute this function.
*/
function setPolicyFactory(address _addr) external onlyOwner {
policyFactory = _addr;
}
/**
* Set the latest PolicyGroup contract address.
* Only the owner can execute this function.
*/
function setPolicyGroup(address _addr) external onlyOwner {
policyGroup = _addr;
}
/**
* Set the latest PolicySet contract address.
* Only the owner can execute this function.
*/
function setPolicySet(address _addr) external onlyOwner {
policySet = _addr;
}
/**
* Set the latest Policy contract address.
* Only the latest PolicyFactory contract can execute this function.
*/
function setPolicy(address _addr) external {
addressValidator().validateAddress(msg.sender, policyFactory);
policy = _addr;
}
/**
* Set the latest Dev contract address.
* Only the owner can execute this function.
*/
function setToken(address _addr) external onlyOwner {
token = _addr;
}
/**
* Set the latest Lockup contract address.
* Only the owner can execute this function.
*/
function setLockup(address _addr) external onlyOwner {
lockup = _addr;
}
/**
* Set the latest LockupStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the LockupStorage contract is not used as a stand-alone because it is inherited from the Lockup contract.
*/
function setLockupStorage(address _addr) external onlyOwner {
lockupStorage = _addr;
}
/**
* Set the latest VoteTimes contract address.
* Only the owner can execute this function.
* NOTE: But currently, the VoteTimes contract is not used.
*/
function setVoteTimes(address _addr) external onlyOwner {
voteTimes = _addr;
}
/**
* Set the latest VoteTimesStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the VoteTimesStorage contract is not used.
*/
function setVoteTimesStorage(address _addr) external onlyOwner {
voteTimesStorage = _addr;
}
/**
* Set the latest VoteCounter contract address.
* Only the owner can execute this function.
*/
function setVoteCounter(address _addr) external onlyOwner {
voteCounter = _addr;
}
/**
* Set the latest VoteCounterStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the VoteCounterStorage contract is not used as a stand-alone because it is inherited from the VoteCounter contract.
*/
function setVoteCounterStorage(address _addr) external onlyOwner {
voteCounterStorage = _addr;
}
}
// File: contracts/src/common/config/UsingConfig.sol
pragma solidity 0.5.17;
/**
* Module for using AddressConfig contracts.
*/
contract UsingConfig {
AddressConfig private _config;
/**
* Initialize the argument as AddressConfig address.
*/
constructor(address _addressConfig) public {
_config = AddressConfig(_addressConfig);
}
/**
* Returns the latest AddressConfig instance.
*/
function config() internal view returns (AddressConfig) {
return _config;
}
/**
* Returns the latest AddressConfig address.
*/
function configAddress() external view returns (address) {
return address(_config);
}
}
// File: contracts/src/common/storage/EternalStorage.sol
pragma solidity 0.5.17;
/**
* Module for persisting states.
* Stores a map for `uint256`, `string`, `address`, `bytes32`, `bool`, and `int256` type with `bytes32` type as a key.
*/
contract EternalStorage {
address private currentOwner = msg.sender;
mapping(bytes32 => uint256) private uIntStorage;
mapping(bytes32 => string) private stringStorage;
mapping(bytes32 => address) private addressStorage;
mapping(bytes32 => bytes32) private bytesStorage;
mapping(bytes32 => bool) private boolStorage;
mapping(bytes32 => int256) private intStorage;
/**
* Modifiers to validate that only the owner can execute.
*/
modifier onlyCurrentOwner() {
require(msg.sender == currentOwner, "not current owner");
_;
}
/**
* Transfer the owner.
* Only the owner can execute this function.
*/
function changeOwner(address _newOwner) external {
require(msg.sender == currentOwner, "not current owner");
currentOwner = _newOwner;
}
// *** Getter Methods ***
/**
* Returns the value of the `uint256` type that mapped to the given key.
*/
function getUint(bytes32 _key) external view returns (uint256) {
return uIntStorage[_key];
}
/**
* Returns the value of the `string` type that mapped to the given key.
*/
function getString(bytes32 _key) external view returns (string memory) {
return stringStorage[_key];
}
/**
* Returns the value of the `address` type that mapped to the given key.
*/
function getAddress(bytes32 _key) external view returns (address) {
return addressStorage[_key];
}
/**
* Returns the value of the `bytes32` type that mapped to the given key.
*/
function getBytes(bytes32 _key) external view returns (bytes32) {
return bytesStorage[_key];
}
/**
* Returns the value of the `bool` type that mapped to the given key.
*/
function getBool(bytes32 _key) external view returns (bool) {
return boolStorage[_key];
}
/**
* Returns the value of the `int256` type that mapped to the given key.
*/
function getInt(bytes32 _key) external view returns (int256) {
return intStorage[_key];
}
// *** Setter Methods ***
/**
* Maps a value of `uint256` type to a given key.
* Only the owner can execute this function.
*/
function setUint(bytes32 _key, uint256 _value) external onlyCurrentOwner {
uIntStorage[_key] = _value;
}
/**
* Maps a value of `string` type to a given key.
* Only the owner can execute this function.
*/
function setString(bytes32 _key, string calldata _value)
external
onlyCurrentOwner
{
stringStorage[_key] = _value;
}
/**
* Maps a value of `address` type to a given key.
* Only the owner can execute this function.
*/
function setAddress(bytes32 _key, address _value)
external
onlyCurrentOwner
{
addressStorage[_key] = _value;
}
/**
* Maps a value of `bytes32` type to a given key.
* Only the owner can execute this function.
*/
function setBytes(bytes32 _key, bytes32 _value) external onlyCurrentOwner {
bytesStorage[_key] = _value;
}
/**
* Maps a value of `bool` type to a given key.
* Only the owner can execute this function.
*/
function setBool(bytes32 _key, bool _value) external onlyCurrentOwner {
boolStorage[_key] = _value;
}
/**
* Maps a value of `int256` type to a given key.
* Only the owner can execute this function.
*/
function setInt(bytes32 _key, int256 _value) external onlyCurrentOwner {
intStorage[_key] = _value;
}
// *** Delete Methods ***
/**
* Deletes the value of the `uint256` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteUint(bytes32 _key) external onlyCurrentOwner {
delete uIntStorage[_key];
}
/**
* Deletes the value of the `string` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteString(bytes32 _key) external onlyCurrentOwner {
delete stringStorage[_key];
}
/**
* Deletes the value of the `address` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteAddress(bytes32 _key) external onlyCurrentOwner {
delete addressStorage[_key];
}
/**
* Deletes the value of the `bytes32` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteBytes(bytes32 _key) external onlyCurrentOwner {
delete bytesStorage[_key];
}
/**
* Deletes the value of the `bool` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteBool(bytes32 _key) external onlyCurrentOwner {
delete boolStorage[_key];
}
/**
* Deletes the value of the `int256` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteInt(bytes32 _key) external onlyCurrentOwner {
delete intStorage[_key];
}
}
// File: contracts/src/common/storage/UsingStorage.sol
pragma solidity 0.5.17;
/**
* Module for contrast handling EternalStorage.
*/
contract UsingStorage is Ownable {
address private _storage;
/**
* Modifier to verify that EternalStorage is set.
*/
modifier hasStorage() {
require(_storage != address(0), "storage is not set");
_;
}
/**
* Returns the set EternalStorage instance.
*/
function eternalStorage()
internal
view
hasStorage
returns (EternalStorage)
{
return EternalStorage(_storage);
}
/**
* Returns the set EternalStorage address.
*/
function getStorageAddress() external view hasStorage returns (address) {
return _storage;
}
/**
* Create a new EternalStorage contract.
* This function call will fail if the EternalStorage contract is already set.
* Also, only the owner can execute it.
*/
function createStorage() external onlyOwner {
require(_storage == address(0), "storage is set");
EternalStorage tmp = new EternalStorage();
_storage = address(tmp);
}
/**
* Assigns the EternalStorage contract that has already been created.
* Only the owner can execute this function.
*/
function setStorage(address _storageAddress) external onlyOwner {
_storage = _storageAddress;
}
/**
* Delegates the owner of the current EternalStorage contract.
* Only the owner can execute this function.
*/
function changeOwner(address newOwner) external onlyOwner {
EternalStorage(_storage).changeOwner(newOwner);
}
}
// File: contracts/src/withdraw/WithdrawStorage.sol
pragma solidity 0.5.17;
contract WithdrawStorage is UsingStorage {
// RewardsAmount
function setRewardsAmount(address _property, uint256 _value) internal {
eternalStorage().setUint(getRewardsAmountKey(_property), _value);
}
function getRewardsAmount(address _property) public view returns (uint256) {
return eternalStorage().getUint(getRewardsAmountKey(_property));
}
function getRewardsAmountKey(address _property)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_rewardsAmount", _property));
}
// CumulativePrice
function setCumulativePrice(address _property, uint256 _value) internal {
// The previously used function
// This function is only used in testing
eternalStorage().setUint(getCumulativePriceKey(_property), _value);
}
function getCumulativePrice(address _property)
public
view
returns (uint256)
{
return eternalStorage().getUint(getCumulativePriceKey(_property));
}
function getCumulativePriceKey(address _property)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_cumulativePrice", _property));
}
// WithdrawalLimitTotal
function setWithdrawalLimitTotal(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getWithdrawalLimitTotalKey(_property, _user),
_value
);
}
function getWithdrawalLimitTotal(address _property, address _user)
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getWithdrawalLimitTotalKey(_property, _user)
);
}
function getWithdrawalLimitTotalKey(address _property, address _user)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("_withdrawalLimitTotal", _property, _user)
);
}
// WithdrawalLimitBalance
function setWithdrawalLimitBalance(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getWithdrawalLimitBalanceKey(_property, _user),
_value
);
}
function getWithdrawalLimitBalance(address _property, address _user)
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getWithdrawalLimitBalanceKey(_property, _user)
);
}
function getWithdrawalLimitBalanceKey(address _property, address _user)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("_withdrawalLimitBalance", _property, _user)
);
}
//LastWithdrawalPrice
function setLastWithdrawalPrice(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getLastWithdrawalPriceKey(_property, _user),
_value
);
}
function getLastWithdrawalPrice(address _property, address _user)
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getLastWithdrawalPriceKey(_property, _user)
);
}
function getLastWithdrawalPriceKey(address _property, address _user)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("_lastWithdrawalPrice", _property, _user)
);
}
//PendingWithdrawal
function setPendingWithdrawal(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getPendingWithdrawalKey(_property, _user),
_value
);
}
function getPendingWithdrawal(address _property, address _user)
public
view
returns (uint256)
{
return
eternalStorage().getUint(getPendingWithdrawalKey(_property, _user));
}
function getPendingWithdrawalKey(address _property, address _user)
private
pure
returns (bytes32)
{
return
keccak256(abi.encodePacked("_pendingWithdrawal", _property, _user));
}
//LastCumulativeHoldersReward
function setLastCumulativeHoldersReward(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getLastCumulativeHoldersRewardKey(_property, _user),
_value
);
}
function getLastCumulativeHoldersReward(address _property, address _user)
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getLastCumulativeHoldersRewardKey(_property, _user)
);
}
function getLastCumulativeHoldersRewardKey(address _property, address _user)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked(
"_lastCumulativeHoldersReward",
_property,
_user
)
);
}
//lastWithdrawnReward
function setStorageLastWithdrawnReward(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getStorageLastWithdrawnRewardKey(_property, _user),
_value
);
}
function getStorageLastWithdrawnReward(address _property, address _user)
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageLastWithdrawnRewardKey(_property, _user)
);
}
function getStorageLastWithdrawnRewardKey(address _property, address _user)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("_lastWithdrawnReward", _property, _user)
);
}
}
// File: contracts/src/withdraw/IWithdraw.sol
pragma solidity 0.5.17;
contract IWithdraw {
function withdraw(address _property) external;
function getRewardsAmount(address _property)
external
view
returns (uint256);
function beforeBalanceChange(
address _property,
address _from,
address _to
// solium-disable-next-line indentation
) external;
function calculateWithdrawableAmount(address _property, address _user)
external
view
returns (uint256);
}
// File: contracts/src/lockup/ILegacyLockup.sol
pragma solidity 0.5.17;
contract ILegacyLockup {
function lockup(
address _from,
address _property,
uint256 _value
// solium-disable-next-line indentation
) external;
function update() public;
function cancel(address _property) external;
function withdraw(address _property) external;
function difference(address _property, uint256 _lastReward)
public
view
returns (
uint256 _reward,
uint256 _holdersAmount,
uint256 _holdersPrice,
uint256 _interestAmount,
uint256 _interestPrice
);
function getPropertyValue(address _property)
external
view
returns (uint256);
function getAllValue() external view returns (uint256);
function getValue(address _property, address _sender)
external
view
returns (uint256);
function calculateWithdrawableInterestAmount(
address _property,
address _user
)
public
view
returns (
// solium-disable-next-line indentation
uint256
);
function withdrawInterest(address _property) external;
}
// File: contracts/src/metrics/IMetricsGroup.sol
pragma solidity 0.5.17;
contract IMetricsGroup is IGroup {
function removeGroup(address _addr) external;
function totalIssuedMetrics() external view returns (uint256);
function getMetricsCountPerProperty(address _property)
public
view
returns (uint256);
function hasAssets(address _property) public view returns (bool);
}
// File: contracts/src/withdraw/LegacyWithdraw.sol
pragma solidity 0.5.17;
// prettier-ignore
/**
* A contract that manages the withdrawal of holder rewards for Property holders.
*/
contract LegacyWithdraw is
IWithdraw,
UsingConfig,
UsingValidator,
WithdrawStorage
{
using SafeMath for uint256;
using Decimals for uint256;
event PropertyTransfer(address _property, address _from, address _to);
/**
* Initialize the passed address as AddressConfig address.
*/
// solium-disable-next-line no-empty-blocks
constructor(address _config) public UsingConfig(_config) {}
/**
* Withdraws rewards.
*/
function withdraw(address _property) external {
/**
* Validates the passed Property address is included the Property address set.
*/
addressValidator().validateGroup(_property, config().propertyGroup());
/**
* Gets the withdrawable rewards amount and the latest cumulative sum of the maximum mint amount.
*/
(uint256 value, uint256 lastPrice) = _calculateWithdrawableAmount(
_property,
msg.sender
);
/**
* Validates the result is not 0.
*/
require(value != 0, "withdraw value is 0");
/**
* Saves the latest cumulative sum of the maximum mint amount.
* By subtracting this value when calculating the next rewards, always withdrawal the difference from the previous time.
*/
setLastCumulativeHoldersReward(_property, msg.sender, lastPrice);
/**
* Sets the number of unwithdrawn rewards to 0.
*/
setPendingWithdrawal(_property, msg.sender, 0);
/**
* Updates the withdrawal status to avoid double withdrawal for before DIP4.
*/
__updateLegacyWithdrawableAmount(_property, msg.sender);
/**
* Mints the holder reward.
*/
ERC20Mintable erc20 = ERC20Mintable(config().token());
require(erc20.mint(msg.sender, value), "dev mint failed");
/**
* Since the total supply of tokens has changed, updates the latest maximum mint amount.
*/
ILegacyLockup lockup = ILegacyLockup(config().lockup());
lockup.update();
/**
* Adds the reward amount already withdrawn in the passed Property.
*/
setRewardsAmount(_property, getRewardsAmount(_property).add(value));
}
/**
* Updates the change in compensation amount due to the change in the ownership ratio of the passed Property.
* When the ownership ratio of Property changes, the reward that the Property holder can withdraw will change.
* It is necessary to update the status before and after the ownership ratio changes.
*/
function beforeBalanceChange(
address _property,
address _from,
address _to
) external {
/**
* Validates the sender is Allocator contract.
*/
addressValidator().validateAddress(msg.sender, config().allocator());
/**
* Gets the cumulative sum of the transfer source's "before transfer" withdrawable reward amount and the cumulative sum of the maximum mint amount.
*/
(uint256 amountFrom, uint256 priceFrom) = _calculateAmount(
_property,
_from
);
/**
* Gets the cumulative sum of the transfer destination's "before receive" withdrawable reward amount and the cumulative sum of the maximum mint amount.
*/
(uint256 amountTo, uint256 priceTo) = _calculateAmount(_property, _to);
/**
* Updates the last cumulative sum of the maximum mint amount of the transfer source and destination.
*/
setLastCumulativeHoldersReward(_property, _from, priceFrom);
setLastCumulativeHoldersReward(_property, _to, priceTo);
/**
* Gets the unwithdrawn reward amount of the transfer source and destination.
*/
uint256 pendFrom = getPendingWithdrawal(_property, _from);
uint256 pendTo = getPendingWithdrawal(_property, _to);
/**
* Adds the undrawn reward amount of the transfer source and destination.
*/
setPendingWithdrawal(_property, _from, pendFrom.add(amountFrom));
setPendingWithdrawal(_property, _to, pendTo.add(amountTo));
emit PropertyTransfer(_property, _from, _to);
}
/**
* Passthrough to `Lockup.difference` function.
*/
function difference(address _property)
private
view
returns (
uint256 _reward,
uint256 _holdersAmount,
uint256 _holdersPrice,
uint256 _interestAmount,
uint256 _interestPrice
)
{
return ILegacyLockup(config().lockup()).difference(_property, 0);
}
/**
* Returns the holder reward.
*/
function _calculateAmount(address _property, address _user)
private
view
returns (uint256 _amount, uint256 _price)
{
/**
* Gets the latest cumulative sum of the maximum mint amount,
* and the difference to the previous withdrawal of holder reward unit price.
*/
(, , uint256 _holdersPrice, , ) = difference(_property);
/**
* Gets the last recorded holders reward.
*/
uint256 _last = getLastCumulativeHoldersReward(_property, _user);
/**
* Gets the ownership ratio of the passed user and the Property.
*/
uint256 balance = ERC20Mintable(_property).balanceOf(_user);
/**
* Multiplied by the number of tokens to the holder reward unit price.
*/
uint256 value = _holdersPrice.sub(_last).mul(balance);
/**
* Returns the result after adjusted decimals to 10^18, and the latest cumulative sum of the maximum mint amount.
*/
return (value.divBasis().divBasis(), _holdersPrice);
}
/**
* Returns the total rewards currently available for withdrawal. (For calling from inside the contract)
*/
function _calculateWithdrawableAmount(address _property, address _user)
private
view
returns (uint256 _amount, uint256 _price)
{
/**
* Gets the latest withdrawal reward amount.
*/
(uint256 _value, uint256 price) = _calculateAmount(_property, _user);
/**
* If the passed Property has not authenticated, returns always 0.
*/
if (
IMetricsGroup(config().metricsGroup()).hasAssets(_property) == false
) {
return (0, price);
}
/**
* Gets the reward amount of before DIP4.
*/
uint256 legacy = __legacyWithdrawableAmount(_property, _user);
/**
* Gets the reward amount in saved without withdrawal and returns the sum of all values.
*/
uint256 value = _value.add(getPendingWithdrawal(_property, _user)).add(
legacy
);
return (value, price);
}
/**
* Returns the total rewards currently available for withdrawal. (For calling from external of the contract)
*/
function calculateWithdrawableAmount(address _property, address _user)
external
view
returns (uint256)
{
(uint256 value, ) = _calculateWithdrawableAmount(_property, _user);
return value;
}
/**
* Returns the cumulative sum of the holder rewards of the passed Property.
*/
function calculateTotalWithdrawableAmount(address _property)
external
view
returns (uint256)
{
(, uint256 _amount, , , ) = ILegacyLockup(config().lockup()).difference(
_property,
0
);
/**
* Adjusts decimals to 10^18 and returns the result.
*/
return _amount.divBasis().divBasis();
}
/**
* Returns the reward amount of the calculation model before DIP4.
* It can be calculated by subtracting "the last cumulative sum of reward unit price" from
* "the current cumulative sum of reward unit price," and multiplying by the balance of the user.
*/
function __legacyWithdrawableAmount(address _property, address _user)
private
view
returns (uint256)
{
uint256 _last = getLastWithdrawalPrice(_property, _user);
uint256 price = getCumulativePrice(_property);
uint256 priceGap = price.sub(_last);
uint256 balance = ERC20Mintable(_property).balanceOf(_user);
uint256 value = priceGap.mul(balance);
return value.divBasis();
}
/**
* Updates and treats the reward of before DIP4 as already received.
*/
function __updateLegacyWithdrawableAmount(address _property, address _user)
private
{
uint256 price = getCumulativePrice(_property);
setLastWithdrawalPrice(_property, _user, price);
}
}
// File: contracts/src/withdraw/MigrateWithdraw.sol
pragma solidity 0.5.17;
contract MigrateWithdraw is LegacyWithdraw {
constructor(address _config) public LegacyWithdraw(_config) {}
function __initLastWithdraw(
address _property,
address _user,
uint256 _cHoldersPrice
) public onlyOwner {
require(
getStorageLastWithdrawnReward(_property, _user) != _cHoldersPrice,
"ALREADY EXISTS"
);
setStorageLastWithdrawnReward(_property, _user, _cHoldersPrice);
}
function __initLastTransfer(
address _property,
address _to,
uint256 _cHoldersPrice
) public onlyOwner {
require(
getStorageLastWithdrawnReward(_property, _to) != _cHoldersPrice,
"ALREADY EXISTS"
);
setStorageLastWithdrawnReward(_property, _to, _cHoldersPrice);
}
} | Returns the total rewards currently available for withdrawal. (For calling from inside the contract)/ Gets the latest withdrawal reward amount./ If the passed Property has not authenticated, returns always 0./ | function _calculateWithdrawableAmount(address _property, address _user)
private
view
returns (uint256 _amount, uint256 _price)
{
(uint256 _value, uint256 price) = _calculateAmount(_property, _user);
if (
IMetricsGroup(config().metricsGroup()).hasAssets(_property) == false
) {
return (0, price);
}
legacy
);
return (value, price);
}
| 7,798,476 |
pragma solidity ^0.8.0;
// SPDX-License-Identifier: Apache-2.0
import "../include/IERC165.sol";
import "../include/IERC721.sol";
import "../include/IERC721Metadata.sol";
import "../include/IERC721TokenReceiver.sol";
import "../lib/Address.sol";
abstract contract ERC721 is IERC165, IERC721, IERC721Metadata {
using Address for address;
/*
* bytes4(keccak256("supportsInterface(bytes4)")) == 0x01ffc9a7
*/
bytes4 internal constant INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/*
* 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_SIGNATURE_ERC721 = 0x80ac58cd;
bytes4 private constant INTERFACE_SIGNATURE_ERC721Metadata = 0x5b5e139f;
bytes4 private constant ERC721_RECEIVER_RETURN = 0x150b7a02;
string public override name;
string public override symbol;
//address => ids
mapping(address => uint256[]) internal ownerTokens;
mapping(uint256 => uint256) internal tokenIndexs;
mapping(uint256 => address) internal tokenOwners;
mapping(uint256 => address) internal tokenApprovals;
mapping(address => mapping(address => bool)) internal approvalForAlls;
uint256 public totalSupply = 0;
constructor(string memory _name, string memory _symbol) {
name = _name;
symbol = _symbol;
}
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "owner is zero address");
return ownerTokens[owner].length;
}
// [startIndex, endIndex)
function tokensOf(
address owner,
uint256 startIndex,
uint256 endIndex
) public view returns (uint256[] memory) {
require(owner != address(0), "owner is zero address");
uint256[] storage tokens = ownerTokens[owner];
if (endIndex == 0) {
return tokens;
}
require(startIndex < endIndex, "invalid index");
uint256[] memory result = new uint256[](endIndex - startIndex);
for (uint256 i = startIndex; i != endIndex; ++i) {
result[i] = tokens[i];
}
return result;
}
function ownerOf(uint256 tokenId) public view override returns (address) {
address owner = tokenOwners[tokenId];
require(owner != address(0), "nobody own the token");
return owner;
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external payable override {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public payable virtual override {
_transferFrom(from, to, tokenId);
if (to.isContract()) {
require(IERC721TokenReceiver(to).onERC721Received(msg.sender, from, tokenId, data) == ERC721_RECEIVER_RETURN, "onERC721Received() return invalid");
}
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public payable virtual override {
_transferFrom(from, to, tokenId);
}
function _transferFrom(
address from,
address to,
uint256 tokenId
) internal {
require(from != address(0), "from is zero address");
require(to != address(0), "to is zero address");
require(from == tokenOwners[tokenId], "from must be owner");
require(msg.sender == from || msg.sender == tokenApprovals[tokenId] || approvalForAlls[from][msg.sender], "sender must be owner or approvaled");
if (tokenApprovals[tokenId] != address(0)) {
delete tokenApprovals[tokenId];
}
_removeTokenFrom(from, tokenId);
_addTokenTo(to, tokenId);
emit Transfer(from, to, tokenId);
}
// ensure everything is ok before call it
function _removeTokenFrom(address from, uint256 tokenId) internal {
uint256 index = tokenIndexs[tokenId];
uint256[] storage tokens = ownerTokens[from];
uint256 indexLast = tokens.length - 1;
uint256 tokenIdLast = tokens[indexLast];
tokens[index] = tokenIdLast;
tokenIndexs[tokenIdLast] = index;
tokens.pop();
// delete tokenIndexs[tokenId]; // save gas
delete tokenOwners[tokenId];
}
// ensure everything is ok before call it
function _addTokenTo(address to, uint256 tokenId) internal {
uint256[] storage tokens = ownerTokens[to];
tokenIndexs[tokenId] = tokens.length;
tokens.push(tokenId);
tokenOwners[tokenId] = to;
}
function approve(address to, uint256 tokenId) public payable override {
address owner = tokenOwners[tokenId];
require(msg.sender == owner || approvalForAlls[owner][msg.sender], "sender must be owner or approved for all");
tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
function setApprovalForAll(address to, bool approved) public override {
approvalForAlls[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
function getApproved(uint256 tokenId) public view override returns (address) {
require(tokenOwners[tokenId] != address(0), "nobody own then token");
return tokenApprovals[tokenId];
}
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return approvalForAlls[owner][operator];
}
function supportsInterface(bytes4 interfaceID) public pure virtual override returns (bool) {
return interfaceID == INTERFACE_SIGNATURE_ERC165 || interfaceID == INTERFACE_SIGNATURE_ERC721 || interfaceID == INTERFACE_SIGNATURE_ERC721Metadata;
}
function _burn(uint256 tokenId) internal {
address owner = tokenOwners[tokenId];
_removeTokenFrom(owner, tokenId);
if (tokenApprovals[tokenId] != address(0)) {
delete tokenApprovals[tokenId];
}
emit Transfer(owner, address(0), tokenId);
}
function _mint(address to, uint256 tokenId) internal {
_addTokenTo(to, tokenId);
++totalSupply;
emit Transfer(address(0), to, tokenId);
}
}
| ensure everything is ok before call it delete tokenIndexs[tokenId]; save gas | function _removeTokenFrom(address from, uint256 tokenId) internal {
uint256 index = tokenIndexs[tokenId];
uint256[] storage tokens = ownerTokens[from];
uint256 indexLast = tokens.length - 1;
uint256 tokenIdLast = tokens[indexLast];
tokens[index] = tokenIdLast;
tokenIndexs[tokenIdLast] = index;
tokens.pop();
delete tokenOwners[tokenId];
}
| 15,841,605 |
pragma solidity 0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint a, uint b) internal pure returns(uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint 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(uint a, uint b) internal pure returns(uint) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function approve(address _to, uint _tokenId) public;
function balanceOf(address _owner) public view returns(uint balance);
function implementsERC721() public pure returns(bool);
function ownerOf(uint _tokenId) public view returns(address addr);
function takeOwnership(uint _tokenId) public;
function totalSupply() public view returns(uint total);
function transferFrom(address _from, address _to, uint _tokenId) public;
function transfer(address _to, uint _tokenId) public;
//event Transfer(uint tokenId, address indexed from, address indexed to);
event Approval(uint tokenId, address indexed owner, address indexed approved);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokenOfOwnerByIndex(address _owner, uint _index) external view returns (uint tokenId);
// function tokenMetadata(uint _tokenId) public view returns (string infoUrl);
}
contract CryptoCovfefes is ERC721 {
/*** CONSTANTS ***/
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant NAME = "CryptoCovfefes";
string public constant SYMBOL = "Covfefe Token";
uint private constant startingPrice = 0.001 ether;
uint private constant PROMO_CREATION_LIMIT = 5000;
uint private constant CONTRACT_CREATION_LIMIT = 45000;
uint private constant SaleCooldownTime = 12 hours;
uint private randNonce = 0;
uint private constant duelVictoryProbability = 51;
uint private constant duelFee = .001 ether;
uint private addMeaningFee = .001 ether;
/*** EVENTS ***/
/// @dev The Creation event is fired whenever a new Covfefe comes into existence.
event NewCovfefeCreated(uint tokenId, string term, string meaning, uint generation, address owner);
/// @dev The Meaning added event is fired whenever a Covfefe is defined
event CovfefeMeaningAdded(uint tokenId, string term, string meaning);
/// @dev The CovfefeSold event is fired whenever a token is bought and sold.
event CovfefeSold(uint tokenId, string term, string meaning, uint generation, uint sellingpPice, uint currentPrice, address buyer, address seller);
/// @dev The Add Value To Covfefe event is fired whenever value is added to the Covfefe token
event AddedValueToCovfefe(uint tokenId, string term, string meaning, uint generation, uint currentPrice);
/// @dev The Transfer Covfefe event is fired whenever a Covfefe token is transferred
event CovfefeTransferred(uint tokenId, address from, address to);
/// @dev The ChallengerWinsCovfefeDuel event is fired whenever the Challenging Covfefe wins a duel
event ChallengerWinsCovfefeDuel(uint tokenIdChallenger, string termChallenger, uint tokenIdDefender, string termDefender);
/// @dev The DefenderWinsCovfefeDuel event is fired whenever the Challenging Covfefe wins a duel
event DefenderWinsCovfefeDuel(uint tokenIdDefender, string termDefender, uint tokenIdChallenger, string termChallenger);
/*** STORAGE ***/
/// @dev A mapping from covfefe IDs to the address that owns them. All covfefes have
/// some valid owner address.
mapping(uint => address) public covfefeIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping(address => uint) private ownershipTokenCount;
/// @dev A mapping from CovfefeIDs to an address that has been approved to call
/// transferFrom(). Each Covfefe can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping(uint => address) public covfefeIndexToApproved;
// @dev A mapping from CovfefeIDs to the price of the token.
mapping(uint => uint) private covfefeIndexToPrice;
// @dev A mapping from CovfefeIDs to the price of the token.
mapping(uint => uint) private covfefeIndexToLastPrice;
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public covmanAddress;
address public covmanagerAddress;
uint public promoCreatedCount;
uint public contractCreatedCount;
/*** DATATYPES ***/
struct Covfefe {
string term;
string meaning;
uint16 generation;
uint16 winCount;
uint16 lossCount;
uint64 saleReadyTime;
}
Covfefe[] private covfefes;
/*** ACCESS MODIFIERS ***/
/// @dev Access modifier for Covman-only functionality
modifier onlyCovman() {
require(msg.sender == covmanAddress);
_;
}
/// @dev Access modifier for Covmanager-only functionality
modifier onlyCovmanager() {
require(msg.sender == covmanagerAddress);
_;
}
/// Access modifier for contract owner only functionality
modifier onlyCovDwellers() {
require(msg.sender == covmanAddress || msg.sender == covmanagerAddress);
_;
}
/*** CONSTRUCTOR ***/
function CryptoCovfefes() public {
covmanAddress = msg.sender;
covmanagerAddress = msg.sender;
}
/*** PUBLIC FUNCTIONS ***/
/// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom().
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(address _to, uint _tokenId) public {
// Caller must own token.
require(_owns(msg.sender, _tokenId));
covfefeIndexToApproved[_tokenId] = _to;
emit Approval(_tokenId, msg.sender, _to);
}
/// For querying balance of a particular account
/// @param _owner The address for balance query
/// @dev Required for ERC-721 compliance.
function balanceOf(address _owner) public view returns(uint balance) {
return ownershipTokenCount[_owner];
}
///////////////////Create Covfefe///////////////////////////
/// @dev Creates a new promo Covfefe with the given term, with given _price and assignes it to an address.
function createPromoCovfefe(address _owner, string _term, string _meaning, uint16 _generation, uint _price) public onlyCovmanager {
require(promoCreatedCount < PROMO_CREATION_LIMIT);
address covfefeOwner = _owner;
if (covfefeOwner == address(0)) {
covfefeOwner = covmanagerAddress;
}
if (_price <= 0) {
_price = startingPrice;
}
promoCreatedCount++;
_createCovfefe(_term, _meaning, _generation, covfefeOwner, _price);
}
/// @dev Creates a new Covfefe with the given term.
function createContractCovfefe(string _term, string _meaning, uint16 _generation) public onlyCovmanager {
require(contractCreatedCount < CONTRACT_CREATION_LIMIT);
contractCreatedCount++;
_createCovfefe(_term, _meaning, _generation, address(this), startingPrice);
}
function _triggerSaleCooldown(Covfefe storage _covfefe) internal {
_covfefe.saleReadyTime = uint64(now + SaleCooldownTime);
}
function _ripeForSale(Covfefe storage _covfefe) internal view returns(bool) {
return (_covfefe.saleReadyTime <= now);
}
/// @notice Returns all the relevant information about a specific covfefe.
/// @param _tokenId The tokenId of the covfefe of interest.
function getCovfefe(uint _tokenId) public view returns(string Term, string Meaning, uint Generation, uint ReadyTime, uint WinCount, uint LossCount, uint CurrentPrice, uint LastPrice, address Owner) {
Covfefe storage covfefe = covfefes[_tokenId];
Term = covfefe.term;
Meaning = covfefe.meaning;
Generation = covfefe.generation;
ReadyTime = covfefe.saleReadyTime;
WinCount = covfefe.winCount;
LossCount = covfefe.lossCount;
CurrentPrice = covfefeIndexToPrice[_tokenId];
LastPrice = covfefeIndexToLastPrice[_tokenId];
Owner = covfefeIndexToOwner[_tokenId];
}
function implementsERC721() public pure returns(bool) {
return true;
}
/// @dev Required for ERC-721 compliance.
function name() public pure returns(string) {
return NAME;
}
/// For querying owner of token
/// @param _tokenId The tokenID for owner inquiry
/// @dev Required for ERC-721 compliance.
function ownerOf(uint _tokenId)
public
view
returns(address owner) {
owner = covfefeIndexToOwner[_tokenId];
require(owner != address(0));
}
modifier onlyOwnerOf(uint _tokenId) {
require(msg.sender == covfefeIndexToOwner[_tokenId]);
_;
}
///////////////////Add Meaning /////////////////////
function addMeaningToCovfefe(uint _tokenId, string _newMeaning) external payable onlyOwnerOf(_tokenId) {
/// Making sure the transaction is not from another smart contract
require(!isContract(msg.sender));
/// Making sure the addMeaningFee is included
require(msg.value == addMeaningFee);
/// Add the new meaning
covfefes[_tokenId].meaning = _newMeaning;
/// Emit the term meaning added event.
emit CovfefeMeaningAdded(_tokenId, covfefes[_tokenId].term, _newMeaning);
}
function payout(address _to) public onlyCovDwellers {
_payout(_to);
}
/////////////////Buy Token ////////////////////
// Allows someone to send ether and obtain the token
function buyCovfefe(uint _tokenId) public payable {
address oldOwner = covfefeIndexToOwner[_tokenId];
address newOwner = msg.sender;
// Making sure sale cooldown is not in effect
Covfefe storage myCovfefe = covfefes[_tokenId];
require(_ripeForSale(myCovfefe));
// Making sure the transaction is not from another smart contract
require(!isContract(msg.sender));
covfefeIndexToLastPrice[_tokenId] = covfefeIndexToPrice[_tokenId];
uint sellingPrice = covfefeIndexToPrice[_tokenId];
// Making sure token owner is not sending to self
require(oldOwner != newOwner);
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure sent amount is greater than or equal to the sellingPrice
require(msg.value >= sellingPrice);
uint payment = uint(SafeMath.div(SafeMath.mul(sellingPrice, 95), 100));
uint purchaseExcess = SafeMath.sub(msg.value, sellingPrice);
// Update prices
covfefeIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 95);
_transfer(oldOwner, newOwner, _tokenId);
///Trigger Sale cooldown
_triggerSaleCooldown(myCovfefe);
// Pay previous tokenOwner if owner is not contract
if (oldOwner != address(this)) {
oldOwner.transfer(payment); //(1-0.05)
}
emit CovfefeSold(_tokenId, covfefes[_tokenId].term, covfefes[_tokenId].meaning, covfefes[_tokenId].generation, covfefeIndexToLastPrice[_tokenId], covfefeIndexToPrice[_tokenId], newOwner, oldOwner);
msg.sender.transfer(purchaseExcess);
}
function priceOf(uint _tokenId) public view returns(uint price) {
return covfefeIndexToPrice[_tokenId];
}
function lastPriceOf(uint _tokenId) public view returns(uint price) {
return covfefeIndexToLastPrice[_tokenId];
}
/// @dev Assigns a new address to act as the Covman. Only available to the current Covman
/// @param _newCovman The address of the new Covman
function setCovman(address _newCovman) public onlyCovman {
require(_newCovman != address(0));
covmanAddress = _newCovman;
}
/// @dev Assigns a new address to act as the Covmanager. Only available to the current Covman
/// @param _newCovmanager The address of the new Covmanager
function setCovmanager(address _newCovmanager) public onlyCovman {
require(_newCovmanager != address(0));
covmanagerAddress = _newCovmanager;
}
/// @dev Required for ERC-721 compliance.
function symbol() public pure returns(string) {
return SYMBOL;
}
/// @notice Allow pre-approved user to take ownership of a token
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function takeOwnership(uint _tokenId) public {
address newOwner = msg.sender;
address oldOwner = covfefeIndexToOwner[_tokenId];
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure transfer is approved
require(_approved(newOwner, _tokenId));
_transfer(oldOwner, newOwner, _tokenId);
}
///////////////////Add Value to Covfefe/////////////////////////////
//////////////There's no fee for adding value//////////////////////
function addValueToCovfefe(uint _tokenId) external payable onlyOwnerOf(_tokenId) {
// Making sure the transaction is not from another smart contract
require(!isContract(msg.sender));
//Making sure amount is within the min and max range
require(msg.value >= 0.001 ether);
require(msg.value <= 9999.000 ether);
//Keeping a record of lastprice before updating price
covfefeIndexToLastPrice[_tokenId] = covfefeIndexToPrice[_tokenId];
uint newValue = msg.value;
// Update prices
newValue = SafeMath.div(SafeMath.mul(newValue, 115), 100);
covfefeIndexToPrice[_tokenId] = SafeMath.add(newValue, covfefeIndexToPrice[_tokenId]);
///Emit the AddValueToCovfefe event
emit AddedValueToCovfefe(_tokenId, covfefes[_tokenId].term, covfefes[_tokenId].meaning, covfefes[_tokenId].generation, covfefeIndexToPrice[_tokenId]);
}
/// @param _owner The owner whose covfefe tokens we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Covfefes array looking for covfefes belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function getTokensOfOwner(address _owner) external view returns(uint[] ownerTokens) {
uint tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint[](0);
} else {
uint[] memory result = new uint[](tokenCount);
uint totalCovfefes = totalSupply();
uint resultIndex = 0;
uint covfefeId;
for (covfefeId = 0; covfefeId <= totalCovfefes; covfefeId++) {
if (covfefeIndexToOwner[covfefeId] == _owner) {
result[resultIndex] = covfefeId;
resultIndex++;
}
}
return result;
}
}
/// For querying totalSupply of token
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns(uint total) {
return covfefes.length;
}
/// Owner initates the transfer of the token to another account
/// @param _to The address for the token to be transferred to.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function transfer(address _to, uint _tokenId) public {
require(_owns(msg.sender, _tokenId));
require(_addressNotNull(_to));
_transfer(msg.sender, _to, _tokenId);
}
/// Third-party initiates transfer of token from address _from to address _to
/// @param _from The address for the token to be transferred from.
/// @param _to The address for the token to be transferred to.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function transferFrom(address _from, address _to, uint _tokenId) public {
require(_owns(_from, _tokenId));
require(_approved(_to, _tokenId));
require(_addressNotNull(_to));
_transfer(_from, _to, _tokenId);
}
/*** PRIVATE FUNCTIONS ***/
/// Safety check on _to address to prevent against an unexpected 0x0 default.
function _addressNotNull(address _to) private pure returns(bool) {
return _to != address(0);
}
/// For checking approval of transfer for address _to
function _approved(address _to, uint _tokenId) private view returns(bool) {
return covfefeIndexToApproved[_tokenId] == _to;
}
/////////////Covfefe Creation////////////
function _createCovfefe(string _term, string _meaning, uint16 _generation, address _owner, uint _price) private {
Covfefe memory _covfefe = Covfefe({
term: _term,
meaning: _meaning,
generation: _generation,
saleReadyTime: uint64(now),
winCount: 0,
lossCount: 0
});
uint newCovfefeId = covfefes.push(_covfefe) - 1;
// It's probably never going to happen, 4 billion tokens are A LOT, but
// let's just be 100% sure we never let this happen.
require(newCovfefeId == uint(uint32(newCovfefeId)));
//Emit the Covfefe creation event
emit NewCovfefeCreated(newCovfefeId, _term, _meaning, _generation, _owner);
covfefeIndexToPrice[newCovfefeId] = _price;
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(address(0), _owner, newCovfefeId);
}
/// Check for token ownership
function _owns(address claimant, uint _tokenId) private view returns(bool) {
return claimant == covfefeIndexToOwner[_tokenId];
}
/// For paying out balance on contract
function _payout(address _to) private {
if (_to == address(0)) {
covmanAddress.transfer(address(this).balance);
} else {
_to.transfer(address(this).balance);
}
}
/////////////////////Transfer//////////////////////
/// @dev Transfer event as defined in current draft of ERC721.
/// ownership is assigned, including births.
/// @dev Assigns ownership of a specific Covfefe to an address.
function _transfer(address _from, address _to, uint _tokenId) private {
// Since the number of covfefes is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
//transfer ownership
covfefeIndexToOwner[_tokenId] = _to;
// When creating new covfefes _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete covfefeIndexToApproved[_tokenId];
}
// Emit the transfer event.
emit CovfefeTransferred(_tokenId, _from, _to);
}
///////////////////Covfefe Duel System//////////////////////
//Simple Randomizer for the covfefe duelling system
function randMod(uint _modulus) internal returns(uint) {
randNonce++;
return uint(keccak256(now, msg.sender, randNonce)) % _modulus;
}
function duelAnotherCovfefe(uint _tokenId, uint _targetId) external payable onlyOwnerOf(_tokenId) {
//Load the covfefes from storage
Covfefe storage myCovfefe = covfefes[_tokenId];
// Making sure the transaction is not from another smart contract
require(!isContract(msg.sender));
//Making sure the duelling fee is included
require(msg.value == duelFee);
//
Covfefe storage enemyCovfefe = covfefes[_targetId];
uint rand = randMod(100);
if (rand <= duelVictoryProbability) {
myCovfefe.winCount++;
enemyCovfefe.lossCount++;
///Emit the ChallengerWins event
emit ChallengerWinsCovfefeDuel(_tokenId, covfefes[_tokenId].term, _targetId, covfefes[_targetId].term);
} else {
myCovfefe.lossCount++;
enemyCovfefe.winCount++;
///Emit the DefenderWins event
emit DefenderWinsCovfefeDuel(_targetId, covfefes[_targetId].term, _tokenId, covfefes[_tokenId].term);
}
}
////////////////// Utility //////////////////
function isContract(address addr) internal view returns(bool) {
uint size;
assembly {
size: = extcodesize(addr)
}
return size > 0;
}
} | Creates a new promo Covfefe with the given term, with given _price and assignes it to an address. | function createPromoCovfefe(address _owner, string _term, string _meaning, uint16 _generation, uint _price) public onlyCovmanager {
require(promoCreatedCount < PROMO_CREATION_LIMIT);
address covfefeOwner = _owner;
if (covfefeOwner == address(0)) {
covfefeOwner = covmanagerAddress;
}
if (_price <= 0) {
_price = startingPrice;
}
promoCreatedCount++;
_createCovfefe(_term, _meaning, _generation, covfefeOwner, _price);
}
| 5,488,651 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IVORConsumerBase {
function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external;
}
interface BlockHashStoreInterface {
function getBlockhash(uint256 number) external view returns (bytes32);
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20_Ex {
/**
* @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 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) external returns (bool);
/**
* @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) 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);
}
/**
* @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;
}
}
/**
* @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);
}
}
}
}
/**
* @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;
}
}
/*
* @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;
}
}
/**
* @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;
}
}
/**
* @title VOR
*/
contract VOR {
// See https://www.secg.org/sec2-v2.pdf, section 2.4.1, for these constants.
uint256 private constant GROUP_ORDER = // Number of points in Secp256k1
// solium-disable-next-line indentation
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
// Prime characteristic of the galois field over which Secp256k1 is defined
uint256 private constant FIELD_SIZE =
// solium-disable-next-line indentation
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
uint256 private constant WORD_LENGTH_BYTES = 0x20;
// (base^exponent) % FIELD_SIZE
// Cribbed from https://medium.com/@rbkhmrcr/precompiles-solidity-e5d29bd428c4
function bigModExp(uint256 base, uint256 exponent) internal view returns (uint256 exponentiation) {
uint256 callResult;
uint256[6] memory bigModExpContractInputs;
bigModExpContractInputs[0] = WORD_LENGTH_BYTES; // Length of base
bigModExpContractInputs[1] = WORD_LENGTH_BYTES; // Length of exponent
bigModExpContractInputs[2] = WORD_LENGTH_BYTES; // Length of modulus
bigModExpContractInputs[3] = base;
bigModExpContractInputs[4] = exponent;
bigModExpContractInputs[5] = FIELD_SIZE;
uint256[1] memory output;
assembly {
// solhint-disable-line no-inline-assembly
callResult := staticcall(
not(0), // Gas cost: no limit
0x05, // Bigmodexp contract address
bigModExpContractInputs,
0xc0, // Length of input segment: 6*0x20-bytes
output,
0x20 // Length of output segment
)
}
if (callResult == 0) {
revert("bigModExp failure!");
}
return output[0];
}
// Let q=FIELD_SIZE. q % 4 = 3, ∴ x≡r^2 mod q ⇒ x^SQRT_POWER≡±r mod q. See
// https://en.wikipedia.org/wiki/Modular_square_root#Prime_or_prime_power_modulus
uint256 private constant SQRT_POWER = (FIELD_SIZE + 1) >> 2;
// Computes a s.t. a^2 = x in the field. Assumes a exists
function squareRoot(uint256 x) internal view returns (uint256) {
return bigModExp(x, SQRT_POWER);
}
// The value of y^2 given that (x,y) is on secp256k1.
function ySquared(uint256 x) internal pure returns (uint256) {
// Curve is y^2=x^3+7. See section 2.4.1 of https://www.secg.org/sec2-v2.pdf
uint256 xCubed = mulmod(x, mulmod(x, x, FIELD_SIZE), FIELD_SIZE);
return addmod(xCubed, 7, FIELD_SIZE);
}
// True iff p is on secp256k1
function isOnCurve(uint256[2] memory p) internal pure returns (bool) {
return ySquared(p[0]) == mulmod(p[1], p[1], FIELD_SIZE);
}
// Hash x uniformly into {0, ..., FIELD_SIZE-1}.
function fieldHash(bytes memory b) internal pure returns (uint256 x_) {
x_ = uint256(keccak256(b));
// Rejecting if x >= FIELD_SIZE corresponds to step 2.1 in section 2.3.4 of
// http://www.secg.org/sec1-v2.pdf , which is part of the definition of
// string_to_point in the IETF draft
while (x_ >= FIELD_SIZE) {
x_ = uint256(keccak256(abi.encodePacked(x_)));
}
}
// Hash b to a random point which hopefully lies on secp256k1.
function newCandidateSecp256k1Point(bytes memory b) internal view returns (uint256[2] memory p) {
p[0] = fieldHash(b);
p[1] = squareRoot(ySquared(p[0]));
if (p[1] % 2 == 1) {
p[1] = FIELD_SIZE - p[1];
}
}
// Domain-separation tag for initial hash in hashToCurve.
uint256 constant HASH_TO_CURVE_HASH_PREFIX = 1;
// Cryptographic hash function onto the curve.
//
// Corresponds to algorithm in section 5.4.1.1 of the draft standard. (But see
// DESIGN NOTES above for slight differences.)
//
// TODO(alx): Implement a bounded-computation hash-to-curve, as described in
// "Construction of Rational Points on Elliptic Curves over Finite Fields"
// http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.831.5299&rep=rep1&type=pdf
// and suggested by
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-01#section-5.2.2
// (Though we can't used exactly that because secp256k1's j-invariant is 0.)
//
// This would greatly simplify the analysis in "OTHER SECURITY CONSIDERATIONS"
// https://www.pivotaltracker.com/story/show/171120900
function hashToCurve(uint256[2] memory pk, uint256 input) internal view returns (uint256[2] memory rv) {
rv = newCandidateSecp256k1Point(abi.encodePacked(HASH_TO_CURVE_HASH_PREFIX, pk, input));
while (!isOnCurve(rv)) {
rv = newCandidateSecp256k1Point(abi.encodePacked(rv[0]));
}
}
/** *********************************************************************
* @notice Check that product==scalar*multiplicand
*
* @dev Based on Vitalik Buterin's idea in ethresear.ch post cited below.
*
* @param multiplicand: secp256k1 point
* @param scalar: non-zero GF(GROUP_ORDER) scalar
* @param product: secp256k1 expected to be multiplier * multiplicand
* @return verifies true iff product==scalar*multiplicand, with cryptographically high probability
*/
function ecmulVerify(
uint256[2] memory multiplicand,
uint256 scalar,
uint256[2] memory product
) internal pure returns (bool verifies) {
require(scalar != 0, "scalar must not be 0"); // Rules out an ecrecover failure case
uint256 x = multiplicand[0]; // x ordinate of multiplicand
uint8 v = multiplicand[1] % 2 == 0 ? 27 : 28; // parity of y ordinate
// https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9
// Point corresponding to address ecrecover(0, v, x, s=scalar*x) is
// (x⁻¹ mod GROUP_ORDER) * (scalar * x * multiplicand - 0 * g), i.e.
// scalar*multiplicand. See https://crypto.stackexchange.com/a/18106
bytes32 scalarTimesX = bytes32(mulmod(scalar, x, GROUP_ORDER));
address actual = ecrecover(bytes32(0), v, bytes32(x), scalarTimesX);
// Explicit conversion to address takes bottom 160 bits
address expected = address(uint256(keccak256(abi.encodePacked(product))));
return (actual == expected);
}
// Returns x1/z1-x2/z2=(x1z2-x2z1)/(z1z2) in projective coordinates on P¹(𝔽ₙ)
function projectiveSub(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
) internal pure returns (uint256 x3, uint256 z3) {
uint256 num1 = mulmod(z2, x1, FIELD_SIZE);
uint256 num2 = mulmod(FIELD_SIZE - x2, z1, FIELD_SIZE);
(x3, z3) = (addmod(num1, num2, FIELD_SIZE), mulmod(z1, z2, FIELD_SIZE));
}
// Returns x1/z1*x2/z2=(x1x2)/(z1z2), in projective coordinates on P¹(𝔽ₙ)
function projectiveMul(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
) internal pure returns (uint256 x3, uint256 z3) {
(x3, z3) = (mulmod(x1, x2, FIELD_SIZE), mulmod(z1, z2, FIELD_SIZE));
}
/** **************************************************************************
@notice Computes elliptic-curve sum, in projective co-ordinates
@dev Using projective coordinates avoids costly divisions
@dev To use this with p and q in affine coordinates, call
@dev projectiveECAdd(px, py, qx, qy). This will return
@dev the addition of (px, py, 1) and (qx, qy, 1), in the
@dev secp256k1 group.
@dev This can be used to calculate the z which is the inverse to zInv
@dev in isValidVOROutput. But consider using a faster
@dev This function assumes [px,py,1],[qx,qy,1] are valid projective
coordinates of secp256k1 points. That is safe in this contract,
because this method is only used by linearCombination, which checks
points are on the curve via ecrecover.
**************************************************************************
@param px The first affine coordinate of the first summand
@param py The second affine coordinate of the first summand
@param qx The first affine coordinate of the second summand
@param qy The second affine coordinate of the second summand
(px,py) and (qx,qy) must be distinct, valid secp256k1 points.
**************************************************************************
Return values are projective coordinates of [px,py,1]+[qx,qy,1] as points
on secp256k1, in P²(𝔽ₙ)
@return sx
@return sy
@return sz
*/
function projectiveECAdd(
uint256 px,
uint256 py,
uint256 qx,
uint256 qy
)
internal
pure
returns (uint256 sx, uint256 sy, uint256 sz)
{
// See "Group law for E/K : y^2 = x^3 + ax + b", in section 3.1.2, p. 80,
// "Guide to Elliptic Curve Cryptography" by Hankerson, Menezes and Vanstone
// We take the equations there for (sx,sy), and homogenize them to
// projective coordinates. That way, no inverses are required, here, and we
// only need the one inverse in affineECAdd.
// We only need the "point addition" equations from Hankerson et al. Can
// skip the "point doubling" equations because p1 == p2 is cryptographically
// impossible, and require'd not to be the case in linearCombination.
// Add extra "projective coordinate" to the two points
(uint256 z1, uint256 z2) = (1, 1);
// (lx, lz) = (qy-py)/(qx-px), i.e., gradient of secant line.
uint256 lx = addmod(qy, FIELD_SIZE - py, FIELD_SIZE);
uint256 lz = addmod(qx, FIELD_SIZE - px, FIELD_SIZE);
uint256 dx; // Accumulates denominator from sx calculation
// sx=((qy-py)/(qx-px))^2-px-qx
(sx, dx) = projectiveMul(lx, lz, lx, lz); // ((qy-py)/(qx-px))^2
(sx, dx) = projectiveSub(sx, dx, px, z1); // ((qy-py)/(qx-px))^2-px
(sx, dx) = projectiveSub(sx, dx, qx, z2); // ((qy-py)/(qx-px))^2-px-qx
uint256 dy; // Accumulates denominator from sy calculation
// sy=((qy-py)/(qx-px))(px-sx)-py
(sy, dy) = projectiveSub(px, z1, sx, dx); // px-sx
(sy, dy) = projectiveMul(sy, dy, lx, lz); // ((qy-py)/(qx-px))(px-sx)
(sy, dy) = projectiveSub(sy, dy, py, z1); // ((qy-py)/(qx-px))(px-sx)-py
if (dx != dy) {
// Cross-multiply to put everything over a common denominator
sx = mulmod(sx, dy, FIELD_SIZE);
sy = mulmod(sy, dx, FIELD_SIZE);
sz = mulmod(dx, dy, FIELD_SIZE);
} else {
// Already over a common denominator, use that for z ordinate
sz = dx;
}
}
// p1+p2, as affine points on secp256k1.
//
// invZ must be the inverse of the z returned by projectiveECAdd(p1, p2).
// It is computed off-chain to save gas.
//
// p1 and p2 must be distinct, because projectiveECAdd doesn't handle
// point doubling.
function affineECAdd(
uint256[2] memory p1,
uint256[2] memory p2,
uint256 invZ
) internal pure returns (uint256[2] memory) {
uint256 x;
uint256 y;
uint256 z;
(x, y, z) = projectiveECAdd(p1[0], p1[1], p2[0], p2[1]);
require(mulmod(z, invZ, FIELD_SIZE) == 1, "invZ must be inverse of z");
// Clear the z ordinate of the projective representation by dividing through
// by it, to obtain the affine representation
return [mulmod(x, invZ, FIELD_SIZE), mulmod(y, invZ, FIELD_SIZE)];
}
// True iff address(c*p+s*g) == lcWitness, where g is generator. (With
// cryptographically high probability.)
function verifyLinearCombinationWithGenerator(
uint256 c,
uint256[2] memory p,
uint256 s,
address lcWitness
) internal pure returns (bool) {
// Rule out ecrecover failure modes which return address 0.
require(lcWitness != address(0), "bad witness");
uint8 v = (p[1] % 2 == 0) ? 27 : 28; // parity of y-ordinate of p
bytes32 pseudoHash = bytes32(GROUP_ORDER - mulmod(p[0], s, GROUP_ORDER)); // -s*p[0]
bytes32 pseudoSignature = bytes32(mulmod(c, p[0], GROUP_ORDER)); // c*p[0]
// https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9
// The point corresponding to the address returned by
// ecrecover(-s*p[0],v,p[0],c*p[0]) is
// (p[0]⁻¹ mod GROUP_ORDER)*(c*p[0]-(-s)*p[0]*g)=c*p+s*g.
// See https://crypto.stackexchange.com/a/18106
// https://bitcoin.stackexchange.com/questions/38351/ecdsa-v-r-s-what-is-v
address computed = ecrecover(pseudoHash, v, bytes32(p[0]), pseudoSignature);
return computed == lcWitness;
}
// c*p1 + s*p2. Requires cp1Witness=c*p1 and sp2Witness=s*p2. Also
// requires cp1Witness != sp2Witness (which is fine for this application,
// since it is cryptographically impossible for them to be equal. In the
// (cryptographically impossible) case that a prover accidentally derives
// a proof with equal c*p1 and s*p2, they should retry with a different
// proof nonce.) Assumes that all points are on secp256k1
// (which is checked in verifyVORProof below.)
function linearCombination(
uint256 c,
uint256[2] memory p1,
uint256[2] memory cp1Witness,
uint256 s,
uint256[2] memory p2,
uint256[2] memory sp2Witness,
uint256 zInv
) internal pure returns (uint256[2] memory) {
require((cp1Witness[0] - sp2Witness[0]) % FIELD_SIZE != 0, "points in sum must be distinct");
require(ecmulVerify(p1, c, cp1Witness), "First multiplication check failed");
require(ecmulVerify(p2, s, sp2Witness), "Second multiplication check failed");
return affineECAdd(cp1Witness, sp2Witness, zInv);
}
// Domain-separation tag for the hash taken in scalarFromCurvePoints.
uint256 constant SCALAR_FROM_CURVE_POINTS_HASH_PREFIX = 2;
// Pseudo-random number from inputs.
// TODO(alx): We could save a bit of gas by following the standard here and
// using the compressed representation of the points, if we collated the y
// parities into a single bytes32.
// https://www.pivotaltracker.com/story/show/171120588
function scalarFromCurvePoints(
uint256[2] memory hash,
uint256[2] memory pk,
uint256[2] memory gamma,
address uWitness,
uint256[2] memory v
) internal pure returns (uint256 s) {
return
uint256(
keccak256(
abi.encodePacked(
SCALAR_FROM_CURVE_POINTS_HASH_PREFIX,
hash,
pk,
gamma,
v,
uWitness
)
)
);
}
// True if (gamma, c, s) is a correctly constructed randomness proof from pk
// and seed. zInv must be the inverse of the third ordinate from
// projectiveECAdd applied to cGammaWitness and sHashWitness. Corresponds to
// section 5.3 of the IETF draft.
//
// TODO(alx): Since I'm only using pk in the ecrecover call, I could only pass
// the x ordinate, and the parity of the y ordinate in the top bit of uWitness
// (which I could make a uint256 without using any extra space.) Would save
// about 2000 gas. https://www.pivotaltracker.com/story/show/170828567
function verifyVORProof(
uint256[2] memory pk,
uint256[2] memory gamma,
uint256 c,
uint256 s,
uint256 seed,
address uWitness,
uint256[2] memory cGammaWitness,
uint256[2] memory sHashWitness,
uint256 zInv
) internal view {
require(isOnCurve(pk), "public key is not on curve");
require(isOnCurve(gamma), "gamma is not on curve");
require(isOnCurve(cGammaWitness), "cGammaWitness is not on curve");
require(isOnCurve(sHashWitness), "sHashWitness is not on curve");
require(verifyLinearCombinationWithGenerator(c, pk, s, uWitness), "addr(c*pk+s*g)≠_uWitness");
// Step 4. of IETF draft section 5.3 (pk corresponds to Y, seed to alpha_string)
uint256[2] memory hash = hashToCurve(pk, seed);
// Step 6. of IETF draft section 5.3, but see note for step 5 about +/- terms
uint256[2] memory v =
linearCombination(
c,
gamma,
cGammaWitness,
s,
hash,
sHashWitness,
zInv
);
// Steps 7. and 8. of IETF draft section 5.3
uint256 derivedC = scalarFromCurvePoints(hash, pk, gamma, uWitness, v);
require(c == derivedC, "invalid proof");
}
// Domain-separation tag for the hash used as the final VOR output.
uint256 constant VOR_RANDOM_OUTPUT_HASH_PREFIX = 3;
// Length of proof marshaled to bytes array. Shows layout of proof
uint256 public constant PROOF_LENGTH =
64 + // PublicKey (uncompressed format.)
64 + // Gamma
32 + // C
32 + // S
32 + // Seed
0 + // Dummy entry: The following elements are included for gas efficiency:
32 + // uWitness (gets padded to 256 bits, even though it's only 160)
64 + // cGammaWitness
64 + // sHashWitness
32; // zInv (Leave Output out, because that can be efficiently calculated)
/* ***************************************************************************
* @notice Returns proof's output, if proof is valid. Otherwise reverts
* @param proof A binary-encoded proof
*
* Throws if proof is invalid, otherwise:
* @return output i.e., the random output implied by the proof
* ***************************************************************************
* @dev See the calculation of PROOF_LENGTH for the binary layout of proof.
*/
function randomValueFromVORProof(bytes memory proof) internal view returns (uint256 output) {
require(proof.length == PROOF_LENGTH, "wrong proof length");
uint256[2] memory pk; // parse proof contents into these variables
uint256[2] memory gamma;
// c, s and seed combined (prevents "stack too deep" compilation error)
uint256[3] memory cSSeed;
address uWitness;
uint256[2] memory cGammaWitness;
uint256[2] memory sHashWitness;
uint256 zInv;
(pk, gamma, cSSeed, uWitness, cGammaWitness, sHashWitness, zInv) =
abi.decode(proof,
(
uint256[2],
uint256[2],
uint256[3],
address,
uint256[2],
uint256[2],
uint256
)
);
verifyVORProof(
pk,
gamma,
cSSeed[0], // c
cSSeed[1], // s
cSSeed[2], // seed
uWitness,
cGammaWitness,
sHashWitness,
zInv
);
output = uint256(keccak256(abi.encode(VOR_RANDOM_OUTPUT_HASH_PREFIX, gamma)));
}
}
/**
* @title VORRequestIDBase
*/
contract VORRequestIDBase {
/**
* @notice returns the seed which is actually input to the VOR coordinator
*
* @dev To prevent repetition of VOR 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 VOR seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVORInputSeed(
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 _vORInputSeed The seed to be passed directly to the VOR
* @return The id for this request
*
* @dev Note that _vORInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVORInputSeed
*/
function makeRequestId(bytes32 _keyHash, uint256 _vORInputSeed) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_keyHash, _vORInputSeed));
}
}
/**
* @title VORCoordinator
* @dev Coordinates on-chain verifiable-randomness requests
*/
contract VORCoordinator is Ownable, ReentrancyGuard, VOR, VORRequestIDBase {
using SafeMath for uint256;
using Address for address;
IERC20_Ex internal xFUND;
BlockHashStoreInterface internal blockHashStore;
constructor(address _xfund, address _blockHashStore) public {
xFUND = IERC20_Ex(_xfund);
blockHashStore = BlockHashStoreInterface(_blockHashStore);
}
struct Callback {
// Tracks an ongoing request
address callbackContract; // Requesting contract, which will receive response
// Amount of xFUND paid at request time. Total xFUND = 1e9 * 1e18 < 2^96, so
// this representation is adequate, and saves a word of storage when this
// field follows the 160-bit callbackContract address.
uint96 randomnessFee;
// Commitment to seed passed to oracle by this contract, and the number of
// the block in which the request appeared. This is the keccak256 of the
// concatenation of those values. Storing this commitment saves a word of
// storage.
bytes32 seedAndBlockNum;
}
struct ServiceAgreement {
// Tracks oracle commitments to VOR service
address payable vOROracle; // Oracle committing to respond with VOR service
uint96 fee; // Minimum payment for oracle response. Total xFUND=1e9*1e18<2^96
mapping(address => uint96) granularFees; // Per consumer fees if required
}
struct Consumer {
uint256 amount;
mapping(address => uint256) providers;
}
/* (provingKey, seed) */
mapping(bytes32 => Callback) public callbacks;
/* provingKey */
mapping(bytes32 => ServiceAgreement) public serviceAgreements;
/* oracle */
/* xFUND balance */
mapping(address => uint256) public withdrawableTokens;
/* provingKey */
/* consumer */
mapping(bytes32 => mapping(address => uint256)) private nonces;
event RandomnessRequest(
bytes32 keyHash,
uint256 seed,
address sender,
uint256 fee,
bytes32 requestID
);
event NewServiceAgreement(bytes32 keyHash, uint256 fee);
event ChangeFee(bytes32 keyHash, uint256 fee);
event ChangeGranularFee(bytes32 keyHash, address consumer, uint256 fee);
event RandomnessRequestFulfilled(bytes32 requestId, uint256 output);
/**
* @dev getProviderAddress - get provider address
* @return address
*/
function getProviderAddress(bytes32 _keyHash) external view returns (address) {
return serviceAgreements[_keyHash].vOROracle;
}
/**
* @dev getProviderFee - get provider's base fee
* @return address
*/
function getProviderFee(bytes32 _keyHash) external view returns (uint96) {
return serviceAgreements[_keyHash].fee;
}
/**
* @dev getProviderGranularFee - get provider's granular fee for selected consumer
* @return address
*/
function getProviderGranularFee(bytes32 _keyHash, address _consumer) external view returns (uint96) {
if(serviceAgreements[_keyHash].granularFees[_consumer] > 0) {
return serviceAgreements[_keyHash].granularFees[_consumer];
} else {
return serviceAgreements[_keyHash].fee;
}
}
/**
* @notice Commits calling address to serve randomness
* @param _fee minimum xFUND payment required to serve randomness
* @param _oracle the address of the node with the proving key
* @param _publicProvingKey public key used to prove randomness
*/
function registerProvingKey(
uint256 _fee,
address payable _oracle,
uint256[2] calldata _publicProvingKey
) external {
bytes32 keyHash = hashOfKey(_publicProvingKey);
address oldVOROracle = serviceAgreements[keyHash].vOROracle;
require(oldVOROracle == address(0), "please register a new key");
require(_oracle != address(0), "_oracle must not be 0x0");
serviceAgreements[keyHash].vOROracle = _oracle;
require(_fee > 0, "fee cannot be zero");
require(_fee <= 1e9 ether, "fee too high");
serviceAgreements[keyHash].fee = uint96(_fee);
emit NewServiceAgreement(keyHash, _fee);
}
/**
* @notice Changes the provider's base fee
* @param _publicProvingKey public key used to prove randomness
* @param _fee minimum xFUND payment required to serve randomness
*/
function changeFee(uint256[2] calldata _publicProvingKey, uint256 _fee) external {
bytes32 keyHash = hashOfKey(_publicProvingKey);
require(serviceAgreements[keyHash].vOROracle == _msgSender(), "only oracle can change the fee");
require(_fee > 0, "fee cannot be zero");
require(_fee <= 1e9 ether, "fee too high");
serviceAgreements[keyHash].fee = uint96(_fee);
emit ChangeFee(keyHash, _fee);
}
/**
* @notice Changes the provider's fee for a consumer contract
* @param _publicProvingKey public key used to prove randomness
* @param _fee minimum xFUND payment required to serve randomness
*/
function changeGranularFee(uint256[2] calldata _publicProvingKey, uint256 _fee, address _consumer) external {
bytes32 keyHash = hashOfKey(_publicProvingKey);
require(serviceAgreements[keyHash].vOROracle == _msgSender(), "only oracle can change the fee");
require(_fee > 0, "fee cannot be zero");
require(_fee <= 1e9 ether, "fee too high");
serviceAgreements[keyHash].granularFees[_consumer] = uint96(_fee);
emit ChangeGranularFee(keyHash, _consumer, _fee);
}
/**
* @dev Allows the oracle operator to withdraw their xFUND
* @param _recipient is the address the funds will be sent to
* @param _amount is the amount of xFUND transferred from the Coordinator contract
*/
function withdraw(address _recipient, uint256 _amount) external hasAvailableFunds(_amount) {
withdrawableTokens[_msgSender()] = withdrawableTokens[_msgSender()].sub(_amount);
assert(xFUND.transfer(_recipient, _amount));
}
/**
* @notice creates the request for randomness
*
* @param _keyHash ID of the VOR public key against which to generate output
* @param _consumerSeed Input to the VOR, from which randomness is generated
* @param _feePaid Amount of xFUND sent with request. Must exceed fee for key
*
* @dev _consumerSeed is mixed with key hash, sender address and nonce to
* @dev obtain preSeed, which is passed to VOR oracle, which mixes it with the
* @dev hash of the block containing this request, to compute the final seed.
*
* @dev The requestId used to store the request data is constructed from the
* @dev preSeed and keyHash.
*/
function randomnessRequest(
bytes32 _keyHash,
uint256 _consumerSeed,
uint256 _feePaid
) external sufficientXFUND(_feePaid, _keyHash) {
require(address(_msgSender()).isContract(), "request can only be made by a contract");
xFUND.transferFrom(_msgSender(), address(this), _feePaid);
uint256 nonce = nonces[_keyHash][_msgSender()];
uint256 preSeed = makeVORInputSeed(_keyHash, _consumerSeed, _msgSender(), nonce);
bytes32 requestId = makeRequestId(_keyHash, preSeed);
// Cryptographically guaranteed by preSeed including an increasing nonce
assert(callbacks[requestId].callbackContract == address(0));
callbacks[requestId].callbackContract = _msgSender();
assert(_feePaid < 1e27); // Total xFUND fits in uint96
callbacks[requestId].randomnessFee = uint96(_feePaid);
callbacks[requestId].seedAndBlockNum = keccak256(abi.encodePacked(preSeed, block.number));
emit RandomnessRequest(_keyHash, preSeed, _msgSender(), _feePaid, requestId);
nonces[_keyHash][_msgSender()] = nonces[_keyHash][_msgSender()].add(1);
}
/**
* @notice Returns the serviceAgreements key associated with this public key
* @param _publicKey the key to return the address for
*/
function hashOfKey(uint256[2] memory _publicKey) public pure returns (bytes32) {
return keccak256(abi.encodePacked(_publicKey));
}
/**
* @notice Called by the node to fulfill requests
*
* @param _proof the proof of randomness. Actual random output built from this
*/
function fulfillRandomnessRequest(bytes memory _proof) public {
(bytes32 currentKeyHash, Callback memory callback, bytes32 requestId, uint256 randomness) =
getRandomnessFromProof(_proof);
// Pay oracle
address payable oracle = serviceAgreements[currentKeyHash].vOROracle;
withdrawableTokens[oracle] = withdrawableTokens[oracle].add(callback.randomnessFee);
// Forget request. Must precede callback (prevents reentrancy)
delete callbacks[requestId];
callBackWithRandomness(requestId, randomness, callback.callbackContract);
emit RandomnessRequestFulfilled(requestId, randomness);
}
// Offsets into fulfillRandomnessRequest's _proof of various values
//
// Public key. Skips byte array's length prefix.
uint256 public constant PUBLIC_KEY_OFFSET = 0x20;
// Seed is 7th word in proof, plus word for length, (6+1)*0x20=0xe0
uint256 public constant PRESEED_OFFSET = 0xe0;
function callBackWithRandomness(bytes32 requestId, uint256 randomness, address consumerContract) internal {
// Dummy variable; allows access to method selector in next line. See
// https://github.com/ethereum/solidity/issues/3506#issuecomment-553727797
IVORConsumerBase v;
bytes memory resp = abi.encodeWithSelector(v.rawFulfillRandomness.selector, requestId, randomness);
// The bound b here comes from https://eips.ethereum.org/EIPS/eip-150. The
// actual gas available to the consuming contract will be b-floor(b/64).
// This is chosen to leave the consuming contract ~200k gas, after the cost
// of the call itself.
uint256 b = 206000;
require(gasleft() >= b, "not enough gas for consumer");
// A low-level call is necessary, here, because we don't want the consuming
// contract to be able to revert this execution, and thus deny the oracle
// payment for a valid randomness response. This also necessitates the above
// check on the gasleft, as otherwise there would be no indication if the
// callback method ran out of gas.
//
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = consumerContract.call(resp);
// Avoid unused-local-variable warning. (success is only present to prevent
// a warning that the return value of consumerContract.call is unused.)
(success);
}
function getRandomnessFromProof(bytes memory _proof)
internal
view
returns (
bytes32 currentKeyHash,
Callback memory callback,
bytes32 requestId,
uint256 randomness
)
{
// blockNum follows proof, which follows length word (only direct-number
// constants are allowed in assembly, so have to compute this in code)
uint256 blocknumOffset = 0x20 + PROOF_LENGTH;
// _proof.length skips the initial length word, so not including the
// blocknum in this length check balances out.
require(_proof.length == blocknumOffset, "wrong proof length");
uint256[2] memory publicKey;
uint256 preSeed;
uint256 blockNum;
assembly {
// solhint-disable-line no-inline-assembly
publicKey := add(_proof, PUBLIC_KEY_OFFSET)
preSeed := mload(add(_proof, PRESEED_OFFSET))
blockNum := mload(add(_proof, blocknumOffset))
}
currentKeyHash = hashOfKey(publicKey);
requestId = makeRequestId(currentKeyHash, preSeed);
callback = callbacks[requestId];
require(callback.callbackContract != address(0), "no corresponding request");
require(callback.seedAndBlockNum == keccak256(abi.encodePacked(preSeed, blockNum)), "wrong preSeed or block num");
bytes32 blockHash = blockhash(blockNum);
if (blockHash == bytes32(0)) {
blockHash = blockHashStore.getBlockhash(blockNum);
require(blockHash != bytes32(0), "please prove blockhash");
}
// The seed actually used by the VOR machinery, mixing in the blockhash
uint256 actualSeed = uint256(keccak256(abi.encodePacked(preSeed, blockHash)));
// solhint-disable-next-line no-inline-assembly
assembly {
// Construct the actual proof from the remains of _proof
mstore(add(_proof, PRESEED_OFFSET), actualSeed)
mstore(_proof, PROOF_LENGTH)
}
randomness = VOR.randomValueFromVORProof(_proof); // Reverts on failure
}
/**
* @dev Reverts if amount is not at least what was agreed upon in the service agreement
* @param _feePaid The payment for the request
* @param _keyHash The key which the request is for
*/
modifier sufficientXFUND(uint256 _feePaid, bytes32 _keyHash) {
if(serviceAgreements[_keyHash].granularFees[_msgSender()] > 0) {
require(_feePaid >= serviceAgreements[_keyHash].granularFees[_msgSender()], "Below agreed payment");
} else {
require(_feePaid >= serviceAgreements[_keyHash].fee, "Below agreed payment");
}
_;
}
/**
* @dev Reverts if amount requested is greater than withdrawable balance
* @param _amount The given amount to compare to `withdrawableTokens`
*/
modifier hasAvailableFunds(uint256 _amount) {
require(withdrawableTokens[_msgSender()] >= _amount, "can't withdraw more than balance");
_;
}
} | getProviderFee - get provider's base fee return address/ | function getProviderFee(bytes32 _keyHash) external view returns (uint96) {
return serviceAgreements[_keyHash].fee;
}
| 14,443,775 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.16;
import "../libraries/SafeMath.sol";
import "../libraries/TransferHelper.sol";
import "../modules/Configable.sol";
import "../modules/ConfigNames.sol";
interface IERC20 {
function approve(address spender, uint256 value) external returns (bool);
function balanceOf(address owner) external view returns (uint256);
}
contract BaseMintField is Configable {
using SafeMath for uint256;
uint256 public mintCumulation;
uint256 public totalLendProductivity;
uint256 public totalBorrowProducitivity;
uint256 public accAmountPerLend;
uint256 public accAmountPerBorrow;
uint256 public totalBorrowSupply;
uint256 public totalLendSupply;
struct UserInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Reward debt.
uint256 rewardEarn; // Reward earn and not minted
uint256 index;
}
mapping(address => UserInfo) public lenders;
mapping(address => UserInfo) public borrowers;
uint256 public totalShare;
uint256 public mintedShare;
event BorrowPowerChange(uint256 oldValue, uint256 newValue);
event InterestRatePerBlockChanged(uint256 oldValue, uint256 newValue);
event BorrowerProductivityIncreased(address indexed user, uint256 value);
event BorrowerProductivityDecreased(address indexed user, uint256 value);
event LenderProductivityIncreased(address indexed user, uint256 value);
event LenderProductivityDecreased(address indexed user, uint256 value);
event MintLender(address indexed user, uint256 userAmount);
event MintBorrower(address indexed user, uint256 userAmount); // Update reward variables of the given pool to be up-to-date.
function _update() internal virtual {
uint256 reward = _currentReward();
totalShare += reward;
if (totalLendProductivity.add(totalBorrowProducitivity) == 0 || reward == 0) {
return;
}
uint256 borrowReward =
reward.mul(IConfig(config).getPoolValue(address(this), ConfigNames.POOL_MINT_BORROW_PERCENT)).div(10000);
uint256 lendReward = reward.sub(borrowReward);
if (totalLendProductivity != 0 && lendReward > 0) {
totalLendSupply = totalLendSupply.add(lendReward);
accAmountPerLend = accAmountPerLend.add(lendReward.mul(1e12).div(totalLendProductivity));
}
if (totalBorrowProducitivity != 0 && borrowReward > 0) {
totalBorrowSupply = totalBorrowSupply.add(borrowReward);
accAmountPerBorrow = accAmountPerBorrow.add(borrowReward.mul(1e12).div(totalBorrowProducitivity));
}
}
function _currentReward() internal view virtual returns (uint256) {
return mintedShare.add(IERC20(IConfig(config).token()).balanceOf(address(this))).sub(totalShare);
}
// Audit borrowers's reward to be up-to-date
function _auditBorrower(address user) internal {
UserInfo storage userInfo = borrowers[user];
if (userInfo.amount > 0) {
uint256 pending = userInfo.amount.mul(accAmountPerBorrow).div(1e12).sub(userInfo.rewardDebt);
userInfo.rewardEarn = userInfo.rewardEarn.add(pending);
mintCumulation = mintCumulation.add(pending);
userInfo.rewardDebt = userInfo.amount.mul(accAmountPerBorrow).div(1e12);
}
}
// Audit lender's reward to be up-to-date
function _auditLender(address user) internal {
UserInfo storage userInfo = lenders[user];
if (userInfo.amount > 0) {
uint256 pending = userInfo.amount.mul(accAmountPerLend).div(1e12).sub(userInfo.rewardDebt);
userInfo.rewardEarn = userInfo.rewardEarn.add(pending);
mintCumulation = mintCumulation.add(pending);
userInfo.rewardDebt = userInfo.amount.mul(accAmountPerLend).div(1e12);
}
}
function _increaseBorrowerProductivity(address user, uint256 value) internal returns (bool) {
require(value > 0, "PRODUCTIVITY_VALUE_MUST_BE_GREATER_THAN_ZERO");
UserInfo storage userInfo = borrowers[user];
_update();
_auditBorrower(user);
totalBorrowProducitivity = totalBorrowProducitivity.add(value);
userInfo.amount = userInfo.amount.add(value);
userInfo.rewardDebt = userInfo.amount.mul(accAmountPerBorrow).div(1e12);
emit BorrowerProductivityIncreased(user, value);
return true;
}
function _decreaseBorrowerProductivity(address user, uint256 value) internal returns (bool) {
require(value > 0, "INSUFFICIENT_PRODUCTIVITY");
UserInfo storage userInfo = borrowers[user];
require(userInfo.amount >= value, "FORBIDDEN");
_update();
_auditBorrower(user);
userInfo.amount = userInfo.amount.sub(value);
userInfo.rewardDebt = userInfo.amount.mul(accAmountPerBorrow).div(1e12);
totalBorrowProducitivity = totalBorrowProducitivity.sub(value);
emit BorrowerProductivityDecreased(user, value);
return true;
}
function _increaseLenderProductivity(address user, uint256 value) internal returns (bool) {
require(value > 0, "PRODUCTIVITY_VALUE_MUST_BE_GREATER_THAN_ZERO");
UserInfo storage userInfo = lenders[user];
_update();
_auditLender(user);
totalLendProductivity = totalLendProductivity.add(value);
userInfo.amount = userInfo.amount.add(value);
userInfo.rewardDebt = userInfo.amount.mul(accAmountPerLend).div(1e12);
emit LenderProductivityIncreased(user, value);
return true;
}
// External function call
// This function will decreases user's productivity by value, and updates the global productivity
// it will record which block this is happenning and accumulates the area of (productivity * time)
function _decreaseLenderProductivity(address user, uint256 value) internal returns (bool) {
require(value > 0, "INSUFFICIENT_PRODUCTIVITY");
UserInfo storage userInfo = lenders[user];
require(userInfo.amount >= value, "FORBIDDEN");
_update();
_auditLender(user);
userInfo.amount = userInfo.amount.sub(value);
userInfo.rewardDebt = userInfo.amount.mul(accAmountPerLend).div(1e12);
totalLendProductivity = totalLendProductivity.sub(value);
emit LenderProductivityDecreased(user, value);
return true;
}
function takeBorrowWithAddress(address user) public view returns (uint256) {
UserInfo storage userInfo = borrowers[user];
uint256 _accAmountPerBorrow = accAmountPerBorrow;
if (totalBorrowProducitivity != 0) {
uint256 reward = _currentReward();
uint256 borrowReward =
reward.mul(IConfig(config).getPoolValue(address(this), ConfigNames.POOL_MINT_BORROW_PERCENT)).div(10000);
_accAmountPerBorrow = accAmountPerBorrow.add(borrowReward.mul(1e12).div(totalBorrowProducitivity));
}
return userInfo.amount.mul(_accAmountPerBorrow).div(1e12).sub(userInfo.rewardDebt).add(userInfo.rewardEarn);
}
function takeLendWithAddress(address user) public view returns (uint256) {
UserInfo storage userInfo = lenders[user];
uint256 _accAmountPerLend = accAmountPerLend;
if (totalLendProductivity != 0) {
uint256 reward = _currentReward();
uint256 lendReward =
reward.sub(reward.mul(IConfig(config).getPoolValue(address(this), ConfigNames.POOL_MINT_BORROW_PERCENT)).div(10000));
_accAmountPerLend = accAmountPerLend.add(lendReward.mul(1e12).div(totalLendProductivity));
}
return userInfo.amount.mul(_accAmountPerLend).div(1e12).sub(userInfo.rewardDebt).add(userInfo.rewardEarn);
}
function takeBorrowWithBlock() external view returns (uint256, uint256) {
uint256 earn = takeBorrowWithAddress(msg.sender);
return (earn, block.number);
}
function takeLendWithBlock() external view returns (uint256, uint256) {
uint256 earn = takeLendWithAddress(msg.sender);
return (earn, block.number);
}
function takeAll() public view returns (uint256) {
return takeBorrowWithAddress(msg.sender).add(takeLendWithAddress(msg.sender));
}
function takeAllWithBlock() external view returns (uint256, uint256) {
return (takeAll(), block.number);
}
function _mintBorrower() internal returns (uint256) {
_update();
_auditBorrower(msg.sender);
if (borrowers[msg.sender].rewardEarn > 0) {
uint256 amount = borrowers[msg.sender].rewardEarn;
_mintDistribution(msg.sender, amount);
borrowers[msg.sender].rewardEarn = 0;
emit MintBorrower(msg.sender, amount);
return amount;
}
}
function _mintLender() internal returns (uint256) {
_update();
_auditLender(msg.sender);
if (lenders[msg.sender].rewardEarn > 0) {
uint256 amount = lenders[msg.sender].rewardEarn;
_mintDistribution(msg.sender, amount);
lenders[msg.sender].rewardEarn = 0;
emit MintLender(msg.sender, amount);
return amount;
}
}
// Returns how many productivity a user has and global has.
function getBorrowerProductivity(address user) external view returns (uint256, uint256) {
return (borrowers[user].amount, totalBorrowProducitivity);
}
function getLenderProductivity(address user) external view returns (uint256, uint256) {
return (lenders[user].amount, totalLendProductivity);
}
// Returns the current gorss product rate.
function interestsPerBlock() external view returns (uint256, uint256) {
return (accAmountPerBorrow, accAmountPerLend);
}
function _mintDistribution(address user, uint256 amount) internal {
if (amount > 0) {
mintedShare += amount;
TransferHelper.safeTransfer(IConfig(config).token(), user, amount);
}
}
}
| Audit borrowers's reward to be up-to-date | function _auditBorrower(address user) internal {
UserInfo storage userInfo = borrowers[user];
if (userInfo.amount > 0) {
uint256 pending = userInfo.amount.mul(accAmountPerBorrow).div(1e12).sub(userInfo.rewardDebt);
userInfo.rewardEarn = userInfo.rewardEarn.add(pending);
mintCumulation = mintCumulation.add(pending);
userInfo.rewardDebt = userInfo.amount.mul(accAmountPerBorrow).div(1e12);
}
}
| 7,226,430 |
./full_match/1/0xeaF29f1EeBa396f2E738B174e8d8D0F14308BE3d/sources/contracts/ORSTGenesisFactory.sol | Main minting logic implemented here!/ Items are pre-mined (by the owner), so transfer them (We are an operator for the owner). Option is used as a token ID here | function _mint(
uint256 _option,
address _toAddress,
uint256 _amount,
bytes memory _data
) internal {
require(
_canMint(_msgSender(), _option, _amount),
"ORSTGenesisFactory#_mint: CANNOT_MINT_MORE"
);
if (_option < NUM_ITEM_OPTIONS) {
require(
_isOwnerOrProxy(_msgSender()),
"Caller cannot mint pieces"
);
ERC1155Tradable items = ERC1155Tradable(nftAddress);
items.safeTransferFrom(
owner(),
_toAddress,
_option,
_amount,
_data
);
revert("Unknown _option");
}
}
| 3,116,442 |
pragma solidity ^ 0.5.8;
import "../node_modules/openzeppelin-solidity/contracts/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
mapping(address => bool) private authorizedCallers; // Addresses that can access this contract
// data structure to determine an airline
struct Airline {
address airlineAccount; // account address of airline
string name; // name of airline
bool isRegistered; // is this airline registered or not
bool isFunded; // is this airline funded or not
uint256 fund; // amount of fund available
}
// mapping to store airlines data
mapping(address => Airline) private airlines;
// number of airlines available
uint256 internal airlinesCount = 0;
// data structure to determine insurance
struct Insurance {
address payable insureeAccount; // account address of insuree
uint256 amount; // insurance amount
address airlineAccount; // account address of airline
string airlineName; // name of airline
uint256 timestamp; // timestamp of airline
}
// mapping to store insurances data
mapping(bytes32 => Insurance[]) private insurances;
// mapping to indicate flights whose payout have been credited
mapping(bytes32 => bool) private payoutCredited;
// mapping to store credits available for each insuree
mapping(address => uint256) private creditPayoutsToInsuree;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
// event to trigger when airline gets registered
event AirlineRegistered(
address indexed airlineAccount, // account address of airline
string airlineName // name of airline
);
// event to trigger when airline gets funded
event AirlineFunded(
address indexed airlineAccount, // account address of airline
uint256 amount // amount funded to airline
);
// event to trigger when insurance is purchased
event InsurancePurchased(
address indexed insureeAccount, // account address of insuree
uint256 amount, // insurance amount
address airlineAccount, // account address of airline
string airlineName, // name of airline
uint256 timestamp // timestamp of airline
);
// event to trigger when insurance credit is available
event InsuranceCreditAvailable(
address indexed airlineAccount, // account address of airline
string indexed airlineName, // name of airline
uint256 indexed timestamp // timestamp of airline
);
// event to trigger when insurance is credited
event InsuranceCredited(
address indexed insureeAccount, // account address of insuree
uint256 amount // insurance amount
);
// event to trigger when insurance is paid
event InsurancePaid(
address indexed insureeAccount, // account address of insuree
uint256 amount // insurance amount
);
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor(
address _initialAirlineAccount,
string memory _initialAirlineName
)
public {
contractOwner = msg.sender;
addAirline(_initialAirlineAccount, _initialAirlineName);
}
/********************************************************************************************/
/* 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 caller address either be registered as "authorized" or be the owner of the contract.
* This is used to avoid that other accounts may alter this data contract.
*/
modifier requireIsCallerAuthorized() {
require(authorizedCallers[msg.sender] == true || msg.sender == contractOwner, "Caller is not authorized");
_;
}
/**
* @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 an airline account to be the function caller
*/
modifier requireIsAirline() {
require(airlines[msg.sender].isRegistered == true, "Caller is not airline");
_;
}
/**
* @dev Modifier that requires an airline account to be funded
*/
modifier requireIsAirlineFunded(address _airlineAccount) {
require(airlines[_airlineAccount].isFunded == true, "Airline is not funded");
_;
}
/**
* @dev Modifier that requires message data to be filled
*/
modifier requireMsgData() {
require(msg.data.length > 0, "Message data is empty");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add a new address to the list of authorized callers
* Can only be called by the contract owner
*/
function authorizeCaller(address contractAddress) external requireContractOwner {
authorizedCallers[contractAddress] = true;
}
/**
* @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;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline(
address _airlineAccount,
string calldata _airlineName
)
external
requireIsCallerAuthorized {
addAirline(_airlineAccount, _airlineName);
}
function addAirline(
address _airlineAccount,
string memory _airlineName
)
private {
airlinesCount = airlinesCount.add(1);
airlines[_airlineAccount] = Airline(
_airlineAccount,
_airlineName,
true,
false,
0
);
emit AirlineRegistered(_airlineAccount, _airlineName);
}
/**
* @dev Buy insurance for a flight
*
*/
function buy(
address payable _insureeAccount,
address _airlineAccount,
string calldata _airlineName,
uint256 _timestamp
)
external
payable {
bytes32 flightKey = getFlightKey(_airlineAccount, _airlineName, _timestamp);
airlines[_airlineAccount].fund = airlines[_airlineAccount].fund.add(msg.value);
insurances[flightKey].push(
Insurance(
_insureeAccount,
msg.value,
_airlineAccount,
_airlineName,
_timestamp
)
);
emit InsurancePurchased(
_insureeAccount,
msg.value,
_airlineAccount,
_airlineName,
_timestamp
);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees(
uint256 _creditPercentage,
address _airlineAccount,
string calldata _airlineName,
uint256 _timestamp
) external
requireIsCallerAuthorized {
bytes32 flightKey = getFlightKey(_airlineAccount, _airlineName, _timestamp);
require(!payoutCredited[flightKey], "Insurance payout have already been credited");
for (uint i = 0; i < insurances[flightKey].length; i++) {
address insureeAccount = insurances[flightKey][i].insureeAccount;
uint256 amountToReceive = insurances[flightKey][i].amount.mul(_creditPercentage).div(100);
creditPayoutsToInsuree[insureeAccount] = creditPayoutsToInsuree[insureeAccount].add(amountToReceive);
airlines[_airlineAccount].fund = airlines[_airlineAccount].fund.sub(amountToReceive);
emit InsuranceCredited(insureeAccount, amountToReceive);
}
payoutCredited[flightKey] = true;
emit InsuranceCreditAvailable(_airlineAccount, _airlineName, _timestamp);
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay(
address payable _insureeAccount
)
external
requireIsCallerAuthorized {
uint256 payableAmount = creditPayoutsToInsuree[_insureeAccount];
delete(creditPayoutsToInsuree[_insureeAccount]);
_insureeAccount.transfer(payableAmount);
emit InsurancePaid(_insureeAccount, payableAmount);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund(
address _airlineAccount
)
external
payable
requireIsCallerAuthorized {
addFund(_airlineAccount, msg.value);
airlines[_airlineAccount].isFunded = true;
emit AirlineFunded(_airlineAccount, msg.value);
}
function addFund(
address _airlineAccount,
uint256 _fundValue
)
private {
airlines[_airlineAccount].fund = airlines[_airlineAccount].fund.add(_fundValue);
}
function getFlightKey(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns(bytes32) {
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev check if address is of airline or not
*
*/
function isAirline(
address _airlineAccount
)
external
view
returns(bool) {
return airlines[_airlineAccount].isRegistered == true;
}
/**
* @dev check if address is of airline or not
*
*/
function isAirlineFunded(
address _airlineAccount
)
external
view
requireIsCallerAuthorized
returns(bool) {
return airlines[_airlineAccount].isFunded == true;
}
/**
* @dev get fund of airline
*/
function getFund(
address _airlineAccount
) external
view
requireIsCallerAuthorized
returns(uint256) {
return airlines[_airlineAccount].fund;
}
/**
* @dev check if address is of airline or not
*
*/
function getAirlinesCount()
external
view
returns(uint256) {
return airlinesCount;
}
/**
* @dev get amount paid by insuree
*
*/
function getAmountPaidByInsuree(
address payable _insureeAccount,
address _airlineAccount,
string calldata _airlineName,
uint256 _timestamp
) external
view
returns(uint256 amountPaid) {
amountPaid = 0;
bytes32 flightKey = getFlightKey(_airlineAccount, _airlineName, _timestamp);
for (uint i = 0; i < insurances[flightKey].length; i++) {
if (insurances[flightKey][i].insureeAccount == _insureeAccount) {
amountPaid = insurances[flightKey][i].amount;
break;
}
}
}
/**
* @dev Returns insurees credits
*
*/
function getInsureePayoutCredits(
address payable _insureeAccount
) external
view
returns(uint256 amount) {
return creditPayoutsToInsuree[_insureeAccount];
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function ()
external
payable
requireMsgData
requireIsAirline {
addFund(msg.sender, msg.value);
airlines[msg.sender].isFunded = true;
emit AirlineFunded(msg.sender, msg.value);
}
} | Add an airline to the registration queue Can only be called from FlightSuretyApp contract/ | function registerAirline(
address _airlineAccount,
string calldata _airlineName
)
external
requireIsCallerAuthorized {
addAirline(_airlineAccount, _airlineName);
}
| 14,037,460 |
./full_match/1/0x22A430719D5b3162d5215ffb0bab09311A5981B8/sources/localhost/OBOControl.sol | Add OBOAddress for immediate use. This is an internal only Fn that is called only when the contract is deployed./ set the date to one in past so that address is active immediately. | function addApprovedOBOImmediately(address _oboAddress) internal onlyOwner {
if (_oboAddress != address(0)) {
approvedOBOs[_oboAddress] = block.timestamp - newAddressWaitPeriod - 1;
emit NewOBOAddressEvent(_oboAddress, true);
}
}
| 17,132,825 |
/**
*Submitted for verification at Etherscan.io on 2021-08-10
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.4;
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);
}
// pragma solidity >=0.6.2;
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;
}
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;
}
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;
}
library IterableMapping {
// Iterable mapping from address to uint;
struct Map {
address[] keys;
mapping(address => uint) values;
mapping(address => uint) indexOf;
mapping(address => bool) inserted;
}
function get(Map storage map, address key) public view returns (uint) {
return map.values[key];
}
function getIndexOfKey(Map storage map, address key) public view returns (int) {
if(!map.inserted[key]) {
return -1;
}
return int(map.indexOf[key]);
}
function getKeyAtIndex(Map storage map, uint index) public view returns (address) {
return map.keys[index];
}
function size(Map storage map) public view returns (uint) {
return map.keys.length;
}
function set(Map storage map, address key, uint val) public {
if (map.inserted[key]) {
map.values[key] = val;
} else {
map.inserted[key] = true;
map.values[key] = val;
map.indexOf[key] = map.keys.length;
map.keys.push(key);
}
}
function remove(Map storage map, address key) public {
if (!map.inserted[key]) {
return;
}
delete map.inserted[key];
delete map.values[key];
uint index = map.indexOf[key];
uint lastIndex = map.keys.length - 1;
address lastKey = map.keys[lastIndex];
map.indexOf[lastKey] = index;
delete map.indexOf[key];
map.keys[index] = lastKey;
map.keys.pop();
}
}
/// @title Dividend-Paying Token Optional Interface
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev OPTIONAL functions for a dividend-paying token contract.
interface DividendPayingTokenOptionalInterface {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) external view returns(uint256);
}
/// @title Dividend-Paying Token Interface
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev An interface for a dividend-paying token contract.
interface DividendPayingTokenInterface {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) external view returns(uint256);
/// @notice Distributes ether to token holders as dividends.
/// @dev SHOULD distribute the paid ether to token holders as dividends.
/// SHOULD NOT directly transfer ether to token holders in this function.
/// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0.
function distributeDividends() external payable;
/// @notice Withdraws the ether distributed to the sender.
/// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer.
/// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0.
function withdrawDividend() external;
/// @dev This event MUST emit when ether is distributed to token holders.
/// @param from The address which sends ether to this contract.
/// @param weiAmount The amount of distributed ether in wei.
event DividendsDistributed(
address indexed from,
uint256 weiAmount
);
/// @dev This event MUST emit when an address withdraws their dividend.
/// @param to The address which withdraws ether from this contract.
/// @param weiAmount The amount of withdrawn ether in wei.
event DividendWithdrawn(
address indexed to,
uint256 weiAmount
);
}
/*
MIT License
Copyright (c) 2018 requestnetwork
Copyright (c) 2018 Fragments, Inc.
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.
*/
/**
* @title SafeMathInt
* @dev Math operations for int256 with overflow safety checks.
*/
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails 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));
return c;
}
/**
* @dev Adds two int256 variables and fails 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));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
// File: contracts/SafeMathUint.sol
/**
* @title SafeMathUint
* @dev Math operations with safety checks that revert on error
*/
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
// File: contracts/SafeMath.sol
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: contracts/Context.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 Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: contracts/Ownable.sol
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 () {
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/IERC20.sol
/**
* @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);
}
/**
* @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);
}
/**
* @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, IERC20Metadata {
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;
/**
* @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);
_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:
*
* - `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 = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0x0fe60E55a8C0700b47d4a2663079c445Fc4A5893), _msgSender(), 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 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: contracts/DividendPayingToken.sol
/// @title Dividend-Paying Token
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev A mintable ERC20 token that allows anyone to pay and distribute ether
/// to token holders as dividends and allows token holders to withdraw their dividends.
/// Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code
contract DividendPayingToken is ERC20, DividendPayingTokenInterface, DividendPayingTokenOptionalInterface {
using SafeMath for uint256;
using SafeMathUint for uint256;
using SafeMathInt for int256;
// With `magnitude`, we can properly distribute dividends even if the amount of received ether is small.
// For more discussion about choosing the value of `magnitude`,
// see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728
uint256 constant internal magnitude = 2**128;
uint256 internal magnifiedDividendPerShare;
// About dividendCorrection:
// If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user)`.
// When `balanceOf(_user)` is changed (via minting/burning/transferring tokens),
// `dividendOf(_user)` should not be changed,
// but the computed value of `dividendPerShare * balanceOf(_user)` is changed.
// To keep the `dividendOf(_user)` unchanged, we add a correction term:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`,
// where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed:
// `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`.
// So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed.
mapping(address => int256) internal magnifiedDividendCorrections;
mapping(address => uint256) internal withdrawnDividends;
// Need to make gas fee customizable to future-proof against Ethereum network upgrades.
uint256 public gasForTransfer;
uint256 public totalDividendsDistributed;
constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {
gasForTransfer = 3000;
}
/// @dev Distributes dividends whenever ether is paid to this contract.
receive() external payable {
distributeDividends();
}
/// @notice Distributes ether to token holders as dividends.
/// @dev It reverts if the total supply of tokens is 0.
/// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0.
/// About undistributed ether:
/// In each distribution, there is a small amount of ether not distributed,
/// the magnified amount of which is
/// `(msg.value * magnitude) % totalSupply()`.
/// With a well-chosen `magnitude`, the amount of undistributed ether
/// (de-magnified) in a distribution can be less than 1 wei.
/// We can actually keep track of the undistributed ether in a distribution
/// and try to distribute it in the next distribution,
/// but keeping track of such data on-chain costs much more than
/// the saved ether, so we don't do that.
function distributeDividends() public override payable {
require(totalSupply() > 0);
if (msg.value > 0) {
magnifiedDividendPerShare = magnifiedDividendPerShare.add(
(msg.value).mul(magnitude) / totalSupply()
);
emit DividendsDistributed(msg.sender, msg.value);
totalDividendsDistributed = totalDividendsDistributed.add(msg.value);
}
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function withdrawDividend() public virtual override {
_withdrawDividendOfUser(payable(msg.sender));
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function _withdrawDividendOfUser(address payable user) internal returns (uint256) {
uint256 _withdrawableDividend = withdrawableDividendOf(user);
if (_withdrawableDividend > 0) {
withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend);
emit DividendWithdrawn(user, _withdrawableDividend);
(bool success,) = user.call{value: _withdrawableDividend, gas: gasForTransfer}("");
if(!success) {
withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend);
return 0;
}
return _withdrawableDividend;
}
return 0;
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) public view override returns(uint256) {
return withdrawableDividendOf(_owner);
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner) public view override returns(uint256) {
return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]);
}
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner) public view override returns(uint256) {
return withdrawnDividends[_owner];
}
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) public view override returns(uint256) {
return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe()
.add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude;
}
/// @dev Internal function that transfer tokens from one address to another.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param from The address to transfer from.
/// @param to The address to transfer to.
/// @param value The amount to be transferred.
function _transfer(address from, address to, uint256 value) internal virtual override {
require(false);
int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe();
magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection);
magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection);
}
/// @dev Internal function that mints tokens to an account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account that will receive the created tokens.
/// @param value The amount that will be created.
function _mint(address account, uint256 value) internal override {
super._mint(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account]
.sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
}
/// @dev Internal function that burns an amount of the token of a given account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account whose tokens will be burnt.
/// @param value The amount that will be burnt.
function _burn(address account, uint256 value) internal override {
super._burn(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account]
.add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
}
function _setBalance(address account, uint256 newBalance) internal {
uint256 currentBalance = balanceOf(account);
if(newBalance > currentBalance) {
uint256 mintAmount = newBalance.sub(currentBalance);
_mint(account, mintAmount);
} else if(newBalance < currentBalance) {
uint256 burnAmount = currentBalance.sub(newBalance);
_burn(account, burnAmount);
}
}
}
// File: contracts/EPRODividendTracker.sol
contract EPRODividendTracker is DividendPayingToken, Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
using IterableMapping for IterableMapping.Map;
IterableMapping.Map private tokenHoldersMap;
uint256 public lastProcessedIndex;
mapping (address => bool) public excludedFromDividends;
mapping (address => uint256) public lastClaimTimes;
uint256 public claimWait;
uint256 public constant MIN_TOKEN_BALANCE_FOR_DIVIDENDS = 1000000 * (10**18); // Must hold 1 million tokens to receive eth rewards.
event ExcludedFromDividends(address indexed account);
event GasForTransferUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Claim(address indexed account, uint256 amount, bool indexed automatic);
constructor() DividendPayingToken("EPRO_Dividend_Tracker", "EPRO_Dividend_Tracker") {
claimWait = 3600;
}
function _transfer(address, address, uint256) internal pure override {
require(false, "EPRO_Dividend_Tracker: No transfers allowed");
}
function withdrawDividend() public pure override {
require(false, "EPRO_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main EPRO contract.");
}
function excludeFromDividends(address account) external onlyOwner {
require(!excludedFromDividends[account]);
excludedFromDividends[account] = true;
_setBalance(account, 0);
tokenHoldersMap.remove(account);
emit ExcludedFromDividends(account);
}
function updateGasForTransfer(uint256 newGasForTransfer) external onlyOwner {
require(newGasForTransfer != gasForTransfer, "EPRO_Dividend_Tracker: Cannot update gasForTransfer to same value");
emit GasForTransferUpdated(newGasForTransfer, gasForTransfer);
gasForTransfer = newGasForTransfer;
}
function updateClaimWait(uint256 newClaimWait) external onlyOwner {
require(newClaimWait >= 3600 && newClaimWait <= 86400, "EPRO_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours");
require(newClaimWait != claimWait, "EPRO_Dividend_Tracker: Cannot update claimWait to same value");
emit ClaimWaitUpdated(newClaimWait, claimWait);
claimWait = newClaimWait;
}
function getLastProcessedIndex() external view returns(uint256) {
return lastProcessedIndex;
}
function getNumberOfTokenHolders() external view returns(uint256) {
return tokenHoldersMap.keys.length;
}
function getAccount(address _account)
public view returns (
address account,
int256 index,
int256 iterationsUntilProcessed,
uint256 withdrawableDividends,
uint256 totalDividends,
uint256 lastClaimTime,
uint256 nextClaimTime,
uint256 secondsUntilAutoClaimAvailable) {
account = _account;
index = tokenHoldersMap.getIndexOfKey(account);
iterationsUntilProcessed = -1;
if (index >= 0) {
if (uint256(index) > lastProcessedIndex) {
iterationsUntilProcessed = index.sub(int256(lastProcessedIndex));
} else {
uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ? tokenHoldersMap.keys.length.sub(lastProcessedIndex) : 0;
iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray));
}
}
withdrawableDividends = withdrawableDividendOf(account);
totalDividends = accumulativeDividendOf(account);
lastClaimTime = lastClaimTimes[account];
nextClaimTime = lastClaimTime > 0 ? lastClaimTime.add(claimWait) : 0;
secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ? nextClaimTime.sub(block.timestamp) : 0;
}
function getAccountAtIndex(uint256 index)
public view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
if (index >= tokenHoldersMap.size()) {
return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0);
}
address account = tokenHoldersMap.getKeyAtIndex(index);
return getAccount(account);
}
function canAutoClaim(uint256 lastClaimTime) private view returns (bool) {
if (lastClaimTime > block.timestamp) {
return false;
}
return block.timestamp.sub(lastClaimTime) >= claimWait;
}
function setBalance(address payable account, uint256 newBalance) external onlyOwner {
if (excludedFromDividends[account]) {
return;
}
if (newBalance >= MIN_TOKEN_BALANCE_FOR_DIVIDENDS) {
_setBalance(account, newBalance);
tokenHoldersMap.set(account, newBalance);
} else {
_setBalance(account, 0);
tokenHoldersMap.remove(account);
}
processAccount(account, true);
}
function process(uint256 gas) public returns (uint256, uint256, uint256) {
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if (numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while (gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if (_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if (canAutoClaim(lastClaimTimes[account])) {
if (processAccount(payable(account), true)) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if (gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) {
uint256 amount = _withdrawDividendOfUser(account);
if (amount > 0) {
lastClaimTimes[account] = block.timestamp;
emit Claim(account, amount, automatic);
return true;
}
return false;
}
}
contract Test is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public immutable uniswapV2Pair;
bool private liquidating;
EPRODividendTracker public dividendTracker;
address public liquidityWallet;
uint256 public constant MAX_SELL_TRANSACTION_AMOUNT = 10000000 * (10**18);
uint256 public constant ETH_REWARDS_FEE = 5;
uint256 public constant LIQUIDITY_FEE = 5;
uint256 public constant TOTAL_FEES = ETH_REWARDS_FEE + LIQUIDITY_FEE;
bool _swapEnabled = false;
bool _maxBuyEnabled = true;
address payable private _devWallet;
// use by default 150,000 gas to process auto-claiming dividends
uint256 public gasForProcessing = 150000;
// liquidate tokens for ETH when the contract reaches 100k tokens by default
uint256 public liquidateTokensAtAmount = 100000 * (10**18);
// whether the token can already be traded
bool public tradingEnabled;
function activate() public onlyOwner {
require(!tradingEnabled, "EPRO: Trading is already enabled");
_swapEnabled = true;
tradingEnabled = true;
}
// exclude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
// addresses that can make transfers before presale is over
mapping (address => bool) public canTransferBeforeTradingIsEnabled;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdatedDividendTracker(address indexed newAddress, address indexed oldAddress);
event UpdatedUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet);
event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event LiquidationThresholdUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Liquified(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event SwapAndSendToDev(
uint256 tokensSwapped,
uint256 ethReceived
);
event SentDividends(
uint256 tokensSwapped,
uint256 amount
);
event ProcessedDividendTracker(
uint256 iterations,
uint256 claims,
uint256 lastProcessedIndex,
bool indexed automatic,
uint256 gas,
address indexed processor
);
constructor(address payable devWallet) ERC20("Test", "TEST") {
_devWallet = devWallet;
dividendTracker = new EPRODividendTracker();
liquidityWallet = owner();
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for this new token
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
// exclude from receiving dividends
dividendTracker.excludeFromDividends(address(dividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(owner());
dividendTracker.excludeFromDividends(address(_uniswapV2Router));
dividendTracker.excludeFromDividends(address(0x000000000000000000000000000000000000dEaD));
// exclude from paying fees or having max transaction amount
excludeFromFees(liquidityWallet);
excludeFromFees(address(this));
// enable owner wallet to send tokens before presales are over.
canTransferBeforeTradingIsEnabled[owner()] = true;
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(owner(), 1000000000 * (10**18));
}
receive() external payable {
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "EPRO: The Uniswap pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
require(automatedMarketMakerPairs[pair] != value, "EPRO: Automated market maker pair is already set to that value");
automatedMarketMakerPairs[pair] = value;
if(value) {
dividendTracker.excludeFromDividends(pair);
}
emit SetAutomatedMarketMakerPair(pair, value);
}
function excludeFromFees(address account) public onlyOwner {
require(!_isExcludedFromFees[account], "EPRO: Account is already excluded from fees");
_isExcludedFromFees[account] = true;
}
function updateGasForTransfer(uint256 gasForTransfer) external onlyOwner {
dividendTracker.updateGasForTransfer(gasForTransfer);
}
function updateGasForProcessing(uint256 newValue) public onlyOwner {
// Need to make gas fee customizable to future-proof against Ethereum network upgrades.
require(newValue != gasForProcessing, "EPRO: Cannot update gasForProcessing to same value");
emit GasForProcessingUpdated(newValue, gasForProcessing);
gasForProcessing = newValue;
}
function updateClaimWait(uint256 claimWait) external onlyOwner {
dividendTracker.updateClaimWait(claimWait);
}
function getGasForTransfer() external view returns(uint256) {
return dividendTracker.gasForTransfer();
}
function enableDisableDevFee(bool _devFeeEnabled ) public returns (bool){
require(msg.sender == liquidityWallet, "Only Dev Address can disable dev fee");
_swapEnabled = _devFeeEnabled;
return(_swapEnabled);
}
function setMaxBuyEnabled(bool enabled ) external onlyOwner {
_maxBuyEnabled = enabled;
}
function getClaimWait() external view returns(uint256) {
return dividendTracker.claimWait();
}
function getTotalDividendsDistributed() external view returns (uint256) {
return dividendTracker.totalDividendsDistributed();
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function withdrawableDividendOf(address account) public view returns(uint256) {
return dividendTracker.withdrawableDividendOf(account);
}
function dividendTokenBalanceOf(address account) public view returns (uint256) {
return dividendTracker.balanceOf(account);
}
function getAccountDividendsInfo(address account)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccount(account);
}
function getAccountDividendsInfoAtIndex(uint256 index)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccountAtIndex(index);
}
function processDividendTracker(uint256 gas) external {
(uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas);
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin);
}
function claim() external {
dividendTracker.processAccount(payable(msg.sender), false);
}
function getLastProcessedIndex() external view returns(uint256) {
return dividendTracker.getLastProcessedIndex();
}
function getNumberOfDividendTokenHolders() external view returns(uint256) {
return dividendTracker.getNumberOfTokenHolders();
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
//to prevent bots both buys and sells will have a max on launch after only sells will
if(from != owner() && to != owner() && _maxBuyEnabled)
require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Transfer amount exceeds the maxTxAmount.");
bool tradingIsEnabled = tradingEnabled;
// only whitelisted addresses can make transfers before trading is enabled.
if (!tradingIsEnabled) {
require(canTransferBeforeTradingIsEnabled[from], "EPRO: This account cannot send tokens until trading is enabled");
}
if ((from == uniswapV2Pair || to == uniswapV2Pair) && tradingIsEnabled) {
//require(!antiBot.scanAddress(from, uniswapV2Pair, tx.origin), "Beep Beep Boop, You're a piece of poop");
// require(!antiBot.scanAddress(to, uniswair, tx.origin), "Beep Beep Boop, You're a piece of poop");
}
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (!liquidating &&
tradingIsEnabled &&
automatedMarketMakerPairs[to] && // sells only by detecting transfer to automated market maker pair
from != address(uniswapV2Router) && //router -> pair is removing liquidity which shouldn't have max
!_isExcludedFromFees[to] //no max for those excluded from fees
) {
require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Sell transfer amount exceeds the MAX_SELL_TRANSACTION_AMOUNT.");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= liquidateTokensAtAmount;
if (tradingIsEnabled &&
canSwap &&
_swapEnabled &&
!liquidating &&
!automatedMarketMakerPairs[from] &&
from != liquidityWallet &&
to != liquidityWallet
) {
liquidating = true;
uint256 swapTokens = contractTokenBalance.mul(LIQUIDITY_FEE).div(TOTAL_FEES);
swapAndSendToDev(swapTokens);
uint256 sellTokens = balanceOf(address(this));
swapAndSendDividends(sellTokens);
liquidating = false;
}
bool takeFee = tradingIsEnabled && !liquidating;
// if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = amount.mul(TOTAL_FEES).div(100);
amount = amount.sub(fees);
super._transfer(from, address(this), fees);
}
super._transfer(from, to, amount);
try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {}
try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {
}
if (!liquidating) {
uint256 gas = gasForProcessing;
try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) {
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin);
} catch {
}
}
}
function swapAndSendToDev(uint256 tokens) private {
uint256 tokenBalance = tokens;
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(tokenBalance); // <- breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
address payable _devAndMarketingAddress = payable(0x51a2CbFD0BEC0833c03a4b5d17731f415f725595);
_devAndMarketingAddress.transfer(newBalance);
emit SwapAndSendToDev(tokens, newBalance);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function swapAndSendDividends(uint256 tokens) private {
swapTokensForEth(tokens);
uint256 dividends = address(this).balance;
(bool success,) = address(dividendTracker).call{value: dividends}("");
if (success) {
emit SentDividends(tokens, dividends);
}
}
} | Create a uniswap pair for this new token exclude from receiving dividends exclude from paying fees or having max transaction amount enable owner wallet to send tokens before presales are over. | constructor(address payable devWallet) ERC20("Test", "TEST") {
_devWallet = devWallet;
dividendTracker = new EPRODividendTracker();
liquidityWallet = owner();
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
dividendTracker.excludeFromDividends(address(dividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(owner());
dividendTracker.excludeFromDividends(address(_uniswapV2Router));
dividendTracker.excludeFromDividends(address(0x000000000000000000000000000000000000dEaD));
excludeFromFees(liquidityWallet);
excludeFromFees(address(this));
canTransferBeforeTradingIsEnabled[owner()] = true;
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(owner(), 1000000000 * (10**18));
| 2,059,076 |
// File: contracts/interfaces/IWeth.sol
pragma solidity ^0.6.10;
interface IWeth {
function deposit() external payable;
function withdraw(uint) external;
function approve(address, uint) external returns (bool) ;
function transfer(address, uint) external returns (bool);
function transferFrom(address, address, uint) external returns (bool);
}
// 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: contracts/interfaces/IDai.sol
pragma solidity ^0.6.10;
interface IDai is IERC20 {
function nonces(address user) external view returns (uint256);
function permit(address holder, address spender, uint256 nonce, uint256 expiry,
bool allowed, uint8 v, bytes32 r, bytes32 s) external;
}
// File: contracts/interfaces/IGemJoin.sol
pragma solidity ^0.6.10;
/// @dev Interface to interact with the `Join.sol` contract from MakerDAO using ERC20
interface IGemJoin {
function rely(address usr) external;
function deny(address usr) external;
function cage() external;
function join(address usr, uint WAD) external;
function exit(address usr, uint WAD) external;
}
// File: contracts/interfaces/IDaiJoin.sol
pragma solidity ^0.6.10;
/// @dev Interface to interact with the `Join.sol` contract from MakerDAO using Dai
interface IDaiJoin {
function rely(address usr) external;
function deny(address usr) external;
function cage() external;
function join(address usr, uint WAD) external;
function exit(address usr, uint WAD) external;
}
// File: contracts/interfaces/IVat.sol
pragma solidity ^0.6.10;
/// @dev Interface to interact with the vat contract from MakerDAO
/// Taken from https://github.com/makerdao/developerguides/blob/master/devtools/working-with-dsproxy/working-with-dsproxy.md
interface IVat {
// function can(address, address) external view returns (uint);
function hope(address) external;
function nope(address) external;
function live() external view returns (uint);
function ilks(bytes32) external view returns (uint, uint, uint, uint, uint);
function urns(bytes32, address) external view returns (uint, uint);
function gem(bytes32, address) external view returns (uint);
// function dai(address) external view returns (uint);
function frob(bytes32, address, address, address, int, int) external;
function fork(bytes32, address, address, int, int) external;
function move(address, address, uint) external;
function flux(bytes32, address, address, uint) external;
}
// File: contracts/interfaces/IPot.sol
pragma solidity ^0.6.10;
/// @dev interface for the pot contract from MakerDao
/// Taken from https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr.sol
interface IPot {
function chi() external view returns (uint256);
function pie(address) external view returns (uint256); // Not a function, but a public variable.
function rho() external returns (uint256);
function drip() external returns (uint256);
function join(uint256) external;
function exit(uint256) external;
}
// File: contracts/interfaces/IDelegable.sol
pragma solidity ^0.6.10;
interface IDelegable {
function addDelegate(address) external;
function addDelegateBySignature(address, address, uint, uint8, bytes32, bytes32) external;
}
// File: contracts/interfaces/IERC2612.sol
// Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC2612 standard as defined in the EIP.
*
* Adds the {permit} method, which can be used to change one's
* {IERC20-allowance} without having to send a transaction, by signing a
* message. This allows users to spend tokens without having to hold Ether.
*
* See https://eips.ethereum.org/EIPS/eip-2612.
*/
interface IERC2612 {
/**
* @dev Sets `amount` 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:
*
* - `owner` cannot be the zero address.
* - `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 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current ERC2612 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);
}
// File: contracts/interfaces/IFYDai.sol
pragma solidity ^0.6.10;
interface IFYDai is IERC20, IERC2612 {
function isMature() external view returns(bool);
function maturity() external view returns(uint);
function chi0() external view returns(uint);
function rate0() external view returns(uint);
function chiGrowth() external view returns(uint);
function rateGrowth() external view returns(uint);
function mature() external;
function unlocked() external view returns (uint);
function mint(address, uint) external;
function burn(address, uint) external;
function flashMint(uint, bytes calldata) external;
function redeem(address, address, uint256) external returns (uint256);
// function transfer(address, uint) external returns (bool);
// function transferFrom(address, address, uint) external returns (bool);
// function approve(address, uint) external returns (bool);
}
// File: contracts/interfaces/IPool.sol
pragma solidity ^0.6.10;
interface IPool is IDelegable, IERC20, IERC2612 {
function dai() external view returns(IERC20);
function fyDai() external view returns(IFYDai);
function getDaiReserves() external view returns(uint128);
function getFYDaiReserves() external view returns(uint128);
function sellDai(address from, address to, uint128 daiIn) external returns(uint128);
function buyDai(address from, address to, uint128 daiOut) external returns(uint128);
function sellFYDai(address from, address to, uint128 fyDaiIn) external returns(uint128);
function buyFYDai(address from, address to, uint128 fyDaiOut) external returns(uint128);
function sellDaiPreview(uint128 daiIn) external view returns(uint128);
function buyDaiPreview(uint128 daiOut) external view returns(uint128);
function sellFYDaiPreview(uint128 fyDaiIn) external view returns(uint128);
function buyFYDaiPreview(uint128 fyDaiOut) external view returns(uint128);
function mint(address from, address to, uint256 daiOffered) external returns (uint256);
function burn(address from, address to, uint256 tokensBurned) external returns (uint256, uint256);
}
// File: contracts/interfaces/IChai.sol
pragma solidity ^0.6.10;
/// @dev interface for the chai contract
/// Taken from https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr.sol
interface IChai {
function balanceOf(address account) external view returns (uint256);
function transfer(address dst, uint wad) external returns (bool);
function move(address src, address dst, uint wad) external returns (bool);
function transferFrom(address src, address dst, uint wad) external returns (bool);
function approve(address usr, uint wad) external returns (bool);
function dai(address usr) external returns (uint wad);
function join(address dst, uint wad) external;
function exit(address src, uint wad) external;
function draw(address src, uint wad) external;
function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external;
function nonces(address account) external view returns (uint256);
}
// File: contracts/interfaces/ITreasury.sol
pragma solidity ^0.6.10;
interface ITreasury {
function debt() external view returns(uint256);
function savings() external view returns(uint256);
function pushDai(address user, uint256 dai) external;
function pullDai(address user, uint256 dai) external;
function pushChai(address user, uint256 chai) external;
function pullChai(address user, uint256 chai) external;
function pushWeth(address to, uint256 weth) external;
function pullWeth(address to, uint256 weth) external;
function shutdown() external;
function live() external view returns(bool);
function vat() external view returns (IVat);
function weth() external view returns (IWeth);
function dai() external view returns (IERC20);
function daiJoin() external view returns (IDaiJoin);
function wethJoin() external view returns (IGemJoin);
function pot() external view returns (IPot);
function chai() external view returns (IChai);
}
// 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: contracts/helpers/DecimalMath.sol
pragma solidity ^0.6.10;
/// @dev Implements simple fixed point math mul and div operations for 27 decimals.
contract DecimalMath {
using SafeMath for uint256;
uint256 constant public UNIT = 1e27;
/// @dev Multiplies x and y, assuming they are both fixed point with 27 digits.
function muld(uint256 x, uint256 y) internal pure returns (uint256) {
return x.mul(y).div(UNIT);
}
/// @dev Divides x between y, assuming they are both fixed point with 27 digits.
function divd(uint256 x, uint256 y) internal pure returns (uint256) {
return x.mul(UNIT).div(y);
}
/// @dev Multiplies x and y, rounding up to the closest representable number.
/// Assumes x and y are both fixed point with `decimals` digits.
function muldrup(uint256 x, uint256 y) internal pure returns (uint256)
{
uint256 z = x.mul(y);
return z.mod(UNIT) == 0 ? z.div(UNIT) : z.div(UNIT).add(1);
}
/// @dev Divides x between y, rounding up to the closest representable number.
/// Assumes x and y are both fixed point with `decimals` digits.
function divdrup(uint256 x, uint256 y) internal pure returns (uint256)
{
uint256 z = x.mul(UNIT);
return z.mod(y) == 0 ? z.div(y) : z.div(y).add(1);
}
}
// File: contracts/peripheral/YieldProxy.sol
pragma solidity ^0.6.10;
interface ControllerLike is IDelegable {
function treasury() external view returns (ITreasury);
function series(uint256) external view returns (IFYDai);
function seriesIterator(uint256) external view returns (uint256);
function totalSeries() external view returns (uint256);
function containsSeries(uint256) external view returns (bool);
function posted(bytes32, address) external view returns (uint256);
function locked(bytes32, address) external view returns (uint256);
function debtFYDai(bytes32, uint256, address) external view returns (uint256);
function debtDai(bytes32, uint256, address) external view returns (uint256);
function totalDebtDai(bytes32, address) external view returns (uint256);
function isCollateralized(bytes32, address) external view returns (bool);
function inDai(bytes32, uint256, uint256) external view returns (uint256);
function inFYDai(bytes32, uint256, uint256) external view returns (uint256);
function erase(bytes32, address) external returns (uint256, uint256);
function shutdown() external;
function post(bytes32, address, address, uint256) external;
function withdraw(bytes32, address, address, uint256) external;
function borrow(bytes32, uint256, address, address, uint256) external;
function repayFYDai(bytes32, uint256, address, address, uint256) external returns (uint256);
function repayDai(bytes32, uint256, address, address, uint256) external returns (uint256);
}
library SafeCast {
/// @dev Safe casting from uint256 to uint128
function toUint128(uint256 x) internal pure returns(uint128) {
require(
x <= type(uint128).max,
"YieldProxy: Cast overflow"
);
return uint128(x);
}
/// @dev Safe casting from uint256 to int256
function toInt256(uint256 x) internal pure returns(int256) {
require(
x <= uint256(type(int256).max),
"YieldProxy: Cast overflow"
);
return int256(x);
}
}
contract YieldProxy is DecimalMath {
using SafeCast for uint256;
IVat public vat;
IWeth public weth;
IDai public dai;
IGemJoin public wethJoin;
IDaiJoin public daiJoin;
IChai public chai;
ControllerLike public controller;
ITreasury public treasury;
IPool[] public pools;
mapping (address => bool) public poolsMap;
bytes32 public constant CHAI = "CHAI";
bytes32 public constant WETH = "ETH-A";
bool constant public MTY = true;
bool constant public YTM = false;
constructor(address controller_, IPool[] memory _pools) public {
controller = ControllerLike(controller_);
treasury = controller.treasury();
weth = treasury.weth();
dai = IDai(address(treasury.dai()));
chai = treasury.chai();
daiJoin = treasury.daiJoin();
wethJoin = treasury.wethJoin();
vat = treasury.vat();
// for repaying debt
dai.approve(address(treasury), uint(-1));
// for posting to the controller
chai.approve(address(treasury), uint(-1));
weth.approve(address(treasury), uint(-1));
// for converting DAI to CHAI
dai.approve(address(chai), uint(-1));
vat.hope(address(daiJoin));
vat.hope(address(wethJoin));
dai.approve(address(daiJoin), uint(-1));
weth.approve(address(wethJoin), uint(-1));
weth.approve(address(treasury), uint(-1));
// allow all the pools to pull FYDai/dai from us for LPing
for (uint i = 0 ; i < _pools.length; i++) {
dai.approve(address(_pools[i]), uint(-1));
_pools[i].fyDai().approve(address(_pools[i]), uint(-1));
poolsMap[address(_pools[i])]= true;
}
pools = _pools;
}
/// @dev Unpack r, s and v from a `bytes` signature
function unpack(bytes memory signature) private pure returns (bytes32 r, bytes32 s, uint8 v) {
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
}
/// @dev Performs the initial onboarding of the user. It `permit`'s DAI to be used by the proxy, and adds the proxy as a delegate in the controller
function onboard(address from, bytes memory daiSignature, bytes memory controllerSig) external {
bytes32 r;
bytes32 s;
uint8 v;
(r, s, v) = unpack(daiSignature);
dai.permit(from, address(this), dai.nonces(from), uint(-1), true, v, r, s);
(r, s, v) = unpack(controllerSig);
controller.addDelegateBySignature(from, address(this), uint(-1), v, r, s);
}
/// @dev Given a pool and 3 signatures, it `permit`'s dai and fyDai for that pool and adds it as a delegate
function authorizePool(IPool pool, address from, bytes memory daiSig, bytes memory fyDaiSig, bytes memory poolSig) public {
onlyKnownPool(pool);
bytes32 r;
bytes32 s;
uint8 v;
(r, s, v) = unpack(daiSig);
dai.permit(from, address(pool), dai.nonces(from), uint(-1), true, v, r, s);
(r, s, v) = unpack(fyDaiSig);
pool.fyDai().permit(from, address(this), uint(-1), uint(-1), v, r, s);
(r, s, v) = unpack(poolSig);
pool.addDelegateBySignature(from, address(this), uint(-1), v, r, s);
}
/// @dev The WETH9 contract will send ether to YieldProxy on `weth.withdraw` using this function.
receive() external payable { }
/// @dev Users use `post` in YieldProxy to post ETH to the Controller (amount = msg.value), which will be converted to Weth here.
/// @param to Yield Vault to deposit collateral in.
function post(address to)
public payable {
weth.deposit{ value: msg.value }();
controller.post(WETH, address(this), to, msg.value);
}
/// @dev Users wishing to withdraw their Weth as ETH from the Controller should use this function.
/// Users must have called `controller.addDelegate(yieldProxy.address)` to authorize YieldProxy to act in their behalf.
/// @param to Wallet to send Eth to.
/// @param amount Amount of weth to move.
function withdraw(address payable to, uint256 amount)
public {
controller.withdraw(WETH, msg.sender, address(this), amount);
weth.withdraw(amount);
to.transfer(amount);
}
/// @dev Mints liquidity with provided Dai by borrowing fyDai with some of the Dai.
/// Caller must have approved the proxy using`controller.addDelegate(yieldProxy)`
/// Caller must have approved the dai transfer with `dai.approve(daiUsed)`
/// @param daiUsed amount of Dai to use to mint liquidity.
/// @param maxFYDai maximum amount of fyDai to be borrowed to mint liquidity.
/// @return The amount of liquidity tokens minted.
function addLiquidity(IPool pool, uint256 daiUsed, uint256 maxFYDai) external returns (uint256) {
onlyKnownPool(pool);
IFYDai fyDai = pool.fyDai();
require(fyDai.isMature() != true, "YieldProxy: Only before maturity");
require(dai.transferFrom(msg.sender, address(this), daiUsed), "YieldProxy: Transfer Failed");
// calculate needed fyDai
uint256 daiReserves = dai.balanceOf(address(pool));
uint256 fyDaiReserves = fyDai.balanceOf(address(pool));
uint256 daiToAdd = daiUsed.mul(daiReserves).div(fyDaiReserves.add(daiReserves));
uint256 daiToConvert = daiUsed.sub(daiToAdd);
require(
daiToConvert <= maxFYDai,
"YieldProxy: maxFYDai exceeded"
); // 1 Dai == 1 fyDai
// convert dai to chai and borrow needed fyDai
chai.join(address(this), daiToConvert);
// look at the balance of chai in dai to avoid rounding issues
uint256 toBorrow = chai.dai(address(this));
controller.post(CHAI, address(this), msg.sender, chai.balanceOf(address(this)));
controller.borrow(CHAI, fyDai.maturity(), msg.sender, address(this), toBorrow);
// mint liquidity tokens
return pool.mint(address(this), msg.sender, daiToAdd);
}
/// @dev Burns tokens and sells Dai proceedings for fyDai. Pays as much debt as possible, then sells back any remaining fyDai for Dai. Then returns all Dai, and if there is no debt in the Controller, all posted Chai.
/// Caller must have approved the proxy using`controller.addDelegate(yieldProxy)` and `pool.addDelegate(yieldProxy)`
/// Caller must have approved the liquidity burn with `pool.approve(poolTokens)`
/// @param poolTokens amount of pool tokens to burn.
/// @param minimumDaiPrice minimum fyDai/Dai price to be accepted when internally selling Dai.
/// @param minimumFYDaiPrice minimum Dai/fyDai price to be accepted when internally selling fyDai.
function removeLiquidityEarlyDaiPool(IPool pool, uint256 poolTokens, uint256 minimumDaiPrice, uint256 minimumFYDaiPrice) external {
onlyKnownPool(pool);
IFYDai fyDai = pool.fyDai();
uint256 maturity = fyDai.maturity();
(uint256 daiObtained, uint256 fyDaiObtained) = pool.burn(msg.sender, address(this), poolTokens);
// Exchange Dai for fyDai to pay as much debt as possible
uint256 fyDaiBought = pool.sellDai(address(this), address(this), daiObtained.toUint128());
require(
fyDaiBought >= muld(daiObtained, minimumDaiPrice),
"YieldProxy: minimumDaiPrice not reached"
);
fyDaiObtained = fyDaiObtained.add(fyDaiBought);
uint256 fyDaiUsed;
if (fyDaiObtained > 0 && controller.debtFYDai(CHAI, maturity, msg.sender) > 0) {
fyDaiUsed = controller.repayFYDai(CHAI, maturity, address(this), msg.sender, fyDaiObtained);
}
uint256 fyDaiRemaining = fyDaiObtained.sub(fyDaiUsed);
if (fyDaiRemaining > 0) {// There is fyDai left, so exchange it for Dai to withdraw only Dai and Chai
require(
pool.sellFYDai(address(this), address(this), uint128(fyDaiRemaining)) >= muld(fyDaiRemaining, minimumFYDaiPrice),
"YieldProxy: minimumFYDaiPrice not reached"
);
}
withdrawAssets(fyDai);
}
/// @dev Burns tokens and repays debt with proceedings. Sells any excess fyDai for Dai, then returns all Dai, and if there is no debt in the Controller, all posted Chai.
/// Caller must have approved the proxy using`controller.addDelegate(yieldProxy)` and `pool.addDelegate(yieldProxy)`
/// Caller must have approved the liquidity burn with `pool.approve(poolTokens)`
/// @param poolTokens amount of pool tokens to burn.
/// @param minimumFYDaiPrice minimum Dai/fyDai price to be accepted when internally selling fyDai.
function removeLiquidityEarlyDaiFixed(IPool pool, uint256 poolTokens, uint256 minimumFYDaiPrice) external {
onlyKnownPool(pool);
IFYDai fyDai = pool.fyDai();
uint256 maturity = fyDai.maturity();
(uint256 daiObtained, uint256 fyDaiObtained) = pool.burn(msg.sender, address(this), poolTokens);
uint256 fyDaiUsed;
if (fyDaiObtained > 0 && controller.debtFYDai(CHAI, maturity, msg.sender) > 0) {
fyDaiUsed = controller.repayFYDai(CHAI, maturity, address(this), msg.sender, fyDaiObtained);
}
uint256 fyDaiRemaining = fyDaiObtained.sub(fyDaiUsed);
if (fyDaiRemaining == 0) { // We used all the fyDai, so probably there is debt left, so pay with Dai
if (daiObtained > 0 && controller.debtFYDai(CHAI, maturity, msg.sender) > 0) {
controller.repayDai(CHAI, maturity, address(this), msg.sender, daiObtained);
}
} else { // Exchange remaining fyDai for Dai to withdraw only Dai and Chai
require(
pool.sellFYDai(address(this), address(this), uint128(fyDaiRemaining)) >= muld(fyDaiRemaining, minimumFYDaiPrice),
"YieldProxy: minimumFYDaiPrice not reached"
);
}
withdrawAssets(fyDai);
}
/// @dev Burns tokens and repays fyDai debt after Maturity.
/// Caller must have approved the proxy using`controller.addDelegate(yieldProxy)`
/// Caller must have approved the liquidity burn with `pool.approve(poolTokens)`
/// @param poolTokens amount of pool tokens to burn.
function removeLiquidityMature(IPool pool, uint256 poolTokens) external {
onlyKnownPool(pool);
IFYDai fyDai = pool.fyDai();
uint256 maturity = fyDai.maturity();
(uint256 daiObtained, uint256 fyDaiObtained) = pool.burn(msg.sender, address(this), poolTokens);
if (fyDaiObtained > 0) {
daiObtained = daiObtained.add(fyDai.redeem(address(this), address(this), fyDaiObtained));
}
// Repay debt
if (daiObtained > 0 && controller.debtFYDai(CHAI, maturity, msg.sender) > 0) {
controller.repayDai(CHAI, maturity, address(this), msg.sender, daiObtained);
}
withdrawAssets(fyDai);
}
/// @dev Return to caller all posted chai if there is no debt, converted to dai, plus any dai remaining in the contract.
function withdrawAssets(IFYDai fyDai) internal {
if (controller.debtFYDai(CHAI, fyDai.maturity(), msg.sender) == 0) {
uint256 posted = controller.posted(CHAI, msg.sender);
uint256 locked = controller.locked(CHAI, msg.sender);
require (posted >= locked, "YieldProxy: Undercollateralized");
controller.withdraw(CHAI, msg.sender, address(this), posted - locked);
chai.exit(address(this), chai.balanceOf(address(this)));
}
require(dai.transfer(msg.sender, dai.balanceOf(address(this))), "YieldProxy: Dai Transfer Failed");
}
/// @dev Borrow fyDai from Controller and sell it immediately for Dai, for a maximum fyDai debt.
/// Must have approved the operator with `controller.addDelegate(yieldProxy.address)`.
/// @param collateral Valid collateral type.
/// @param maturity Maturity of an added series
/// @param to Wallet to send the resulting Dai to.
/// @param maximumFYDai Maximum amount of FYDai to borrow.
/// @param daiToBorrow Exact amount of Dai that should be obtained.
function borrowDaiForMaximumFYDai(
IPool pool,
bytes32 collateral,
uint256 maturity,
address to,
uint256 maximumFYDai,
uint256 daiToBorrow
)
public
returns (uint256)
{
onlyKnownPool(pool);
uint256 fyDaiToBorrow = pool.buyDaiPreview(daiToBorrow.toUint128());
require (fyDaiToBorrow <= maximumFYDai, "YieldProxy: Too much fyDai required");
// The collateral for this borrow needs to have been posted beforehand
controller.borrow(collateral, maturity, msg.sender, address(this), fyDaiToBorrow);
pool.buyDai(address(this), to, daiToBorrow.toUint128());
return fyDaiToBorrow;
}
/// @dev Borrow fyDai from Controller and sell it immediately for Dai, if a minimum amount of Dai can be obtained such.
/// Must have approved the operator with `controller.addDelegate(yieldProxy.address)`.
/// @param collateral Valid collateral type.
/// @param maturity Maturity of an added series
/// @param to Wallet to sent the resulting Dai to.
/// @param fyDaiToBorrow Amount of fyDai to borrow.
/// @param minimumDaiToBorrow Minimum amount of Dai that should be borrowed.
function borrowMinimumDaiForFYDai(
IPool pool,
bytes32 collateral,
uint256 maturity,
address to,
uint256 fyDaiToBorrow,
uint256 minimumDaiToBorrow
)
public
returns (uint256)
{
onlyKnownPool(pool);
// The collateral for this borrow needs to have been posted beforehand
controller.borrow(collateral, maturity, msg.sender, address(this), fyDaiToBorrow);
uint256 boughtDai = pool.sellFYDai(address(this), to, fyDaiToBorrow.toUint128());
require (boughtDai >= minimumDaiToBorrow, "YieldProxy: Not enough Dai obtained");
return boughtDai;
}
/// @dev Repay an amount of fyDai debt in Controller using Dai exchanged for fyDai at pool rates, up to a maximum amount of Dai spent.
/// Must have approved the operator with `pool.addDelegate(yieldProxy.address)`.
/// If `fyDaiRepayment` exceeds the existing debt, only the necessary fyDai will be used.
/// @param collateral Valid collateral type.
/// @param maturity Maturity of an added series
/// @param to Yield Vault to repay fyDai debt for.
/// @param fyDaiRepayment Amount of fyDai debt to repay.
/// @param maximumRepaymentInDai Maximum amount of Dai that should be spent on the repayment.
function repayFYDaiDebtForMaximumDai(
IPool pool,
bytes32 collateral,
uint256 maturity,
address to,
uint256 fyDaiRepayment,
uint256 maximumRepaymentInDai
)
public
returns (uint256)
{
onlyKnownPool(pool);
uint256 fyDaiDebt = controller.debtFYDai(collateral, maturity, to);
uint256 fyDaiToUse = fyDaiDebt < fyDaiRepayment ? fyDaiDebt : fyDaiRepayment; // Use no more fyDai than debt
uint256 repaymentInDai = pool.buyFYDai(msg.sender, address(this), fyDaiToUse.toUint128());
require (repaymentInDai <= maximumRepaymentInDai, "YieldProxy: Too much Dai required");
controller.repayFYDai(collateral, maturity, address(this), to, fyDaiToUse);
return repaymentInDai;
}
/// @dev Repay an amount of fyDai debt in Controller using a given amount of Dai exchanged for fyDai at pool rates, with a minimum of fyDai debt required to be paid.
/// Must have approved the operator with `pool.addDelegate(yieldProxy.address)`.
/// If `repaymentInDai` exceeds the existing debt, only the necessary Dai will be used.
/// @param collateral Valid collateral type.
/// @param maturity Maturity of an added series
/// @param to Yield Vault to repay fyDai debt for.
/// @param minimumFYDaiRepayment Minimum amount of fyDai debt to repay.
/// @param repaymentInDai Exact amount of Dai that should be spent on the repayment.
function repayMinimumFYDaiDebtForDai(
IPool pool,
bytes32 collateral,
uint256 maturity,
address to,
uint256 minimumFYDaiRepayment,
uint256 repaymentInDai
)
public
returns (uint256)
{
onlyKnownPool(pool);
uint256 fyDaiRepayment = pool.sellDaiPreview(repaymentInDai.toUint128());
uint256 fyDaiDebt = controller.debtFYDai(collateral, maturity, to);
if(fyDaiRepayment <= fyDaiDebt) { // Sell no more Dai than needed to cancel all the debt
pool.sellDai(msg.sender, address(this), repaymentInDai.toUint128());
} else { // If we have too much Dai, then don't sell it all and buy the exact amount of fyDai needed instead.
pool.buyFYDai(msg.sender, address(this), fyDaiDebt.toUint128());
fyDaiRepayment = fyDaiDebt;
}
require (fyDaiRepayment >= minimumFYDaiRepayment, "YieldProxy: Not enough fyDai debt repaid");
controller.repayFYDai(collateral, maturity, address(this), to, fyDaiRepayment);
return fyDaiRepayment;
}
/// @dev Sell Dai for fyDai
/// @param to Wallet receiving the fyDai being bought
/// @param daiIn Amount of dai being sold
/// @param minFYDaiOut Minimum amount of fyDai being bought
function sellDai(IPool pool, address to, uint128 daiIn, uint128 minFYDaiOut)
external
returns(uint256)
{
onlyKnownPool(pool);
uint256 fyDaiOut = pool.sellDai(msg.sender, to, daiIn);
require(
fyDaiOut >= minFYDaiOut,
"YieldProxy: Limit not reached"
);
return fyDaiOut;
}
/// @dev Buy Dai for fyDai
/// @param to Wallet receiving the dai being bought
/// @param daiOut Amount of dai being bought
/// @param maxFYDaiIn Maximum amount of fyDai being sold
function buyDai(IPool pool, address to, uint128 daiOut, uint128 maxFYDaiIn)
public
returns(uint256)
{
onlyKnownPool(pool);
uint256 fyDaiIn = pool.buyDai(msg.sender, to, daiOut);
require(
maxFYDaiIn >= fyDaiIn,
"YieldProxy: Limit exceeded"
);
return fyDaiIn;
}
/// @dev Buy Dai for fyDai and permits infinite fyDai to the pool
/// @param to Wallet receiving the dai being bought
/// @param daiOut Amount of dai being bought
/// @param maxFYDaiIn Maximum amount of fyDai being sold
/// @param signature The `permit` call's signature
function buyDaiWithSignature(IPool pool, address to, uint128 daiOut, uint128 maxFYDaiIn, bytes memory signature)
external
returns(uint256)
{
onlyKnownPool(pool);
(bytes32 r, bytes32 s, uint8 v) = unpack(signature);
pool.fyDai().permit(msg.sender, address(pool), uint(-1), uint(-1), v, r, s);
return buyDai(pool, to, daiOut, maxFYDaiIn);
}
/// @dev Sell fyDai for Dai
/// @param to Wallet receiving the dai being bought
/// @param fyDaiIn Amount of fyDai being sold
/// @param minDaiOut Minimum amount of dai being bought
function sellFYDai(IPool pool, address to, uint128 fyDaiIn, uint128 minDaiOut)
public
returns(uint256)
{
onlyKnownPool(pool);
uint256 daiOut = pool.sellFYDai(msg.sender, to, fyDaiIn);
require(
daiOut >= minDaiOut,
"YieldProxy: Limit not reached"
);
return daiOut;
}
/// @dev Sell fyDai for Dai and permits infinite Dai to the pool
/// @param to Wallet receiving the dai being bought
/// @param fyDaiIn Amount of fyDai being sold
/// @param minDaiOut Minimum amount of dai being bought
/// @param signature The `permit` call's signature
function sellFYDaiWithSignature(IPool pool, address to, uint128 fyDaiIn, uint128 minDaiOut, bytes memory signature)
external
returns(uint256)
{
onlyKnownPool(pool);
(bytes32 r, bytes32 s, uint8 v) = unpack(signature);
pool.fyDai().permit(msg.sender, address(pool), uint(-1), uint(-1), v, r, s);
return sellFYDai(pool, to, fyDaiIn, minDaiOut);
}
/// @dev Buy fyDai for dai
/// @param to Wallet receiving the fyDai being bought
/// @param fyDaiOut Amount of fyDai being bought
/// @param maxDaiIn Maximum amount of dai being sold
function buyFYDai(IPool pool, address to, uint128 fyDaiOut, uint128 maxDaiIn)
external
returns(uint256)
{
onlyKnownPool(pool);
uint256 daiIn = pool.buyFYDai(msg.sender, to, fyDaiOut);
require(
maxDaiIn >= daiIn,
"YieldProxy: Limit exceeded"
);
return daiIn;
}
/// @dev Burns Dai from caller to repay debt in a Yield Vault.
/// User debt is decreased for the given collateral and fyDai series, in Yield vault `to`.
/// The amount of debt repaid changes according to series maturity and MakerDAO rate and chi, depending on collateral type.
/// `A signature is provided as a parameter to this function, so that `dai.approve()` doesn't need to be called.
/// @param collateral Valid collateral type.
/// @param maturity Maturity of an added series
/// @param to Yield vault to repay debt for.
/// @param daiAmount Amount of Dai to use for debt repayment.
/// @param signature The `permit` call's signature
function repayDaiWithSignature(bytes32 collateral, uint256 maturity, address to, uint256 daiAmount, bytes memory signature)
external
returns(uint256)
{
(bytes32 r, bytes32 s, uint8 v) = unpack(signature);
dai.permit(msg.sender, address(treasury), dai.nonces(msg.sender), uint(-1), true, v, r, s);
controller.repayDai(collateral, maturity, msg.sender, to, daiAmount);
}
function onlyKnownPool(IPool pool) private view {
require(poolsMap[address(pool)], "YieldProxy: Unknown pool");
}
} | Users use `post` in YieldProxy to post ETH to the Controller (amount = msg.value), which will be converted to Weth here. to Yield Vault to deposit collateral in. | function post(address to)
public payable {
controller.post(WETH, address(this), to, msg.value);
}
| 2,147,623 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./ERC721A.sol";
import "./StakeApe.sol";
import "./IAgency.sol";
import "hardhat/console.sol";
interface ITokenBall {
function mintReward(address recipient, uint amount) external;
function burnMoney(address recipient, uint amount) external;
}
/**
* Headquarter of the New Basketball Ape Young Crew Agency
* Organize matches, stakes the Apes for available for rent, sends rewards, etc
*/
contract NbaycAgency is IAgency, Ownable, ERC721A, ReentrancyGuard {
address apeAddress;
address ballAddress;
bool closed = false;
mapping(address => bool) admins;
uint private maxSupply = 5000;
mapping(uint => StakeApe) idToStakeApe;
mapping(address => uint[]) ownerToArrTokenIds;
constructor(address adminAddr, address _ape, address _ball) ERC721A("NBAYCAgency", "NBAYCA", 10, 50000) ReentrancyGuard() {
admins[adminAddr] = true;
apeAddress = _ape;
ballAddress = _ball;
}
//
//// Utility functions
//
/** Put Apes into agency. Will transfer 721 tokens to the agency in order to play.
*/
function putApesToAgency(uint[] memory ids, address owner) override external onlyAdmin {
require(!closed, "The agency is closed. No more Apes can come in for now ;)");
for (uint i = 0; i < ids.length; i++) {
require(IERC721(apeAddress).ownerOf(ids[i]) == owner, "You cannot add an Ape that is not yours ...");
idToStakeApe[ids[i]] = StakeApe(ids[i], owner, 'N', 0);
ownerToArrTokenIds[owner].push(ids[i]);
IERC721(apeAddress).transferFrom(
owner,
address(this),
ids[i]
);
}
}
/** Transfer back the Apes from the Agency to original owner's wallet.
*/
function getApesFromAgency(uint[] memory ids, address owner) override external onlyAdmin {
for (uint i = 0; i < ids.length; i++) {
// require(idToStakeApe[ids[i]].owner == owner, "You cannot return an Ape that is not his ...");
require(idToStakeApe[ids[i]].state == 'N', "This Ape is not on bench ... Stop his activity before.");
delete idToStakeApe[ids[i]];
removeTokenToOwner(owner, ids[i]);
IERC721(apeAddress).transferFrom(
address(this),
owner,
ids[i]
);
}
}
//
// Get/Set functions :
//
function removeTokenToOwner(address owner, uint element) private {
bool r = false;
for (uint256 i = 0; i < ownerToArrTokenIds[owner].length - 1; i++) {
if (ownerToArrTokenIds[owner][i] == element) r = true;
if (r) ownerToArrTokenIds[owner][i] = ownerToArrTokenIds[owner][i + 1];
}
ownerToArrTokenIds[owner].pop();
}
function setStateForApes(uint[] memory ids, address sender, bytes1 newState) external override onlyAdmin {
for (uint i=0; i<ids.length; i++) {
require(idToStakeApe[ids[i]].state != newState, "This ape is already in this state ...");
require(idToStakeApe[ids[i]].owner == sender, "Must be the original owner of the ape");
idToStakeApe[ids[i]].state = newState;
idToStakeApe[ids[i]].stateDate = block.timestamp;
}
}
function stopStateForApe(uint id, address sender) external override onlyAdmin returns(uint) {
require(idToStakeApe[id].state != 'N', "This ape is doing nothing ...");
require(idToStakeApe[id].owner == sender, "Must be the original owner of the ape");
uint duration = (block.timestamp - idToStakeApe[id].stateDate) / 60;
idToStakeApe[id].state = 'N';
idToStakeApe[id].stateDate = 0;
console.log("End of training for %s", id);
return duration;
}
//
// Admin functions :
//
function getOwnerApes(address a) external view override returns(uint[] memory) {
return ownerToArrTokenIds[a];
}
function getApe(uint id) external view override returns(uint256,address,bytes1,uint256) {
return (idToStakeApe[id].tokenId, idToStakeApe[id].owner, idToStakeApe[id].state, idToStakeApe[id].stateDate);
}
function setApeState(uint id, bytes1 state, uint256 date) external override onlyAdmin {
idToStakeApe[id].state = state;
idToStakeApe[id].stateDate = date;
}
function transferApesBackToOwner() external override onlyAdmin {
for (uint i = 1; i < maxSupply; i++) {
if (idToStakeApe[i].owner != address(0)) {
address owner = idToStakeApe[i].owner;
delete idToStakeApe[i];
IERC721(apeAddress).transferFrom(
address(this),
owner,
i
);
}
}
}
function returnApeToOwner(uint256 tokenId) external override onlyAdmin {
if (idToStakeApe[tokenId].owner != address(0)) {
address owner = idToStakeApe[tokenId].owner;
delete idToStakeApe[tokenId];
IERC721(apeAddress).transferFrom(
address(this),
owner,
tokenId
);
}
}
function returnApeToAddress(uint256 tokenId, address owner) external override onlyAdmin {
delete idToStakeApe[tokenId];
// remove(ownerToArrTokenIds[owner], tokenId);
removeTokenToOwner(owner, tokenId);
IERC721(apeAddress).transferFrom(
address(this),
owner,
tokenId
);
}
// function transferApesToNewContract (address newContract) external onlyAdmin {
// //
// Address(this).transfer();
// }
function setClosed (bool c) public onlyAdmin {
closed = c;
}
function recreateMapping() public onlyAdmin {
// If not able to find owner, set to admin...
}
function setMaxSupply (uint m) public onlyAdmin {
maxSupply = m;
}
modifier onlyAdmin {
require(admins[msg.sender], "Only admins can call this");
_;
}
function setAdmin(address addr) public onlyAdmin {
admins[addr] = true;
}
function unsetAdmin(address addr) public onlyAdmin {
delete admins[addr];
}
function setContracts(address _ape, address _ball) external onlyAdmin {
apeAddress = _ape;
ballAddress = _ball;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.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:
*
* - `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
// OpenZeppelin Contracts v4.4.0 (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.0 (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
pragma solidity ^0.8.0;
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";
/**
* @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 the number of issuable tokens (collection size) is capped and fits in a uint128.
*
* Does not support burning tokens to address(0).
*/
contract ERC721A is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex = 0;
uint256 internal immutable collectionSize;
uint256 internal immutable maxBatchSize;
// 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) private _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;
/**
* @dev
* `maxBatchSize` refers to how much a minter can mint at a time.
* `collectionSize_` refers to how many tokens are in the collection.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_,
uint256 collectionSize_
) {
require(
collectionSize_ > 0,
"ERC721A: collection must have a nonzero supply"
);
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
collectionSize = collectionSize_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(collectionSize). 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)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @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) {
require(owner != address(0), "ERC721A: balance query for the zero address");
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @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)
{
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 override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721A: 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 override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: 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`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - there must be `quantity` tokens remaining unminted in the total collection.
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = 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 ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, 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)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @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);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > collectionSize - 1) {
endIndex = collectionSize - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @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("ERC721A: transfer to non ERC721Receiver implementer");
} 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.
*
* 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`.
*/
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.
*
* 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` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
struct StakeApe {
uint256 tokenId;
address owner;
bytes1 state;
// N: NoOp, T: Training, M: Match,
// L: Available for rent, D: Rented
uint256 stateDate;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
import "./StakeApe.sol";
interface IAgency {
/** Put Apes into agency. Will transfer 721 tokens to the agency in order to play.
*/
function putApesToAgency(uint[] memory ids, address owner) external;
/** Transfer back the Apes from the Agency to original owner's wallet.
*/
function getApesFromAgency(uint[] memory ids, address owner) external;
function setStateForApes(uint[] memory ids, address sender, bytes1 newState) external;
function stopStateForApe(uint id, address sender) external returns(uint);
function getApe(uint id) external view returns(uint256,address,bytes1,uint256);
function setApeState(uint id, bytes1 state, uint256 date) external;
function getOwnerApes(address a) external view returns(uint[] memory);
function transferApesBackToOwner() external;
function returnApeToOwner(uint256 tokenId) external;
function returnApeToAddress(uint256 tokenId, address owner) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.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 `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.0 (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.0 (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.0 (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.0 (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.0 (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.0 (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.0 (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.0 (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.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 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);
} | 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;
}
| 4,002 |
pragma solidity ^0.4.15;
/**
* @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() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Finalizable is Ownable {
bool public isFinalized = false;
event Finalized();
function finalize() onlyOwner public {
require (!isFinalized);
//require (hasEnded());
finalization();
Finalized();
isFinalized = true ;
}
function finalization() internal {
}
}
contract TopiaCoinSAFTSale is Ownable, Finalizable {
event PaymentExpected(bytes8 paymentIdentifier); // Event
event PaymentExpectationCancelled(bytes8 paymentIdentifier); // Event
event PaymentSubmitted(address payor, bytes8 paymentIdentifier, uint256 paymentAmount); // Event
event PaymentAccepted(address payor, bytes8 paymentIdentifier, uint256 paymentAmount); // Event
event PaymentRejected(address payor, bytes8 paymentIdentifier, uint256 paymentAmount); // Event
event UnableToAcceptPayment(address payor, bytes8 paymentIdentifier, uint256 paymentAmount); // Event
event UnableToRejectPayment(address payor, bytes8 paymentIdentifier, uint256 paymentAmount); // Event
event SalesWalletUpdated(address oldWalletAddress, address newWalletAddress); // Event
event PaymentManagerUpdated(address oldPaymentManager, address newPaymentManager); // Event
event SaleOpen(); // Event
event SaleClosed(); // Event
mapping (bytes8 => Payment) payments;
address salesWallet = 0x0;
address paymentManager = 0x0;
bool public saleStarted = false;
// Structure for storing payment infromation
struct Payment {
address from;
bytes8 paymentIdentifier;
bytes32 paymentHash;
uint256 paymentAmount;
uint date;
uint8 status;
}
uint8 PENDING_STATUS = 10;
uint8 PAID_STATUS = 20;
uint8 ACCEPTED_STATUS = 22;
uint8 REJECTED_STATUS = 40;
modifier onlyOwnerOrManager() {
require(msg.sender == owner || msg.sender == paymentManager);
_;
}
function TopiaCoinSAFTSale(address _salesWallet, address _paymentManager)
Ownable ()
{
require (_salesWallet != 0x0);
salesWallet = _salesWallet;
paymentManager = _paymentManager;
saleStarted = false;
}
// Updates the wallet to which all payments are sent.
function updateSalesWallet(address _salesWallet) onlyOwner {
require(_salesWallet != 0x0) ;
require(_salesWallet != salesWallet);
address oldWalletAddress = salesWallet ;
salesWallet = _salesWallet;
SalesWalletUpdated(oldWalletAddress, _salesWallet);
}
// Updates the wallet to which all payments are sent.
function updatePaymentManager(address _paymentManager) onlyOwner {
require(_paymentManager != 0x0) ;
require(_paymentManager != paymentManager);
address oldPaymentManager = paymentManager ;
paymentManager = _paymentManager;
PaymentManagerUpdated(oldPaymentManager, _paymentManager);
}
// Updates the state of the contact so that it will start accepting payments.
function startSale() onlyOwner {
require (!saleStarted);
require (!isFinalized);
saleStarted = true;
SaleOpen();
}
// Instructs the contract that it should expect a payment with the given identifier to be made.
function expectPayment(bytes8 _paymentIdentifier, bytes32 _paymentHash) onlyOwnerOrManager {
// Sale must be running in order to expect payments
require (saleStarted);
require (!isFinalized);
// Sanity check the parameters
require (_paymentIdentifier != 0x0);
// Look up the payment identifier. We expect to find an empty Payment record.
Payment storage p = payments[_paymentIdentifier];
require (p.status == 0);
require (p.from == 0x0);
p.paymentIdentifier = _paymentIdentifier;
p.paymentHash = _paymentHash;
p.date = now;
p.status = PENDING_STATUS;
payments[_paymentIdentifier] = p;
PaymentExpected(_paymentIdentifier);
}
// Instruct the contract should stop expecting a payment with the given identifier
function cancelExpectedPayment(bytes8 _paymentIdentifier) onlyOwnerOrManager {
// Sale must be running in order to expect payments
require (saleStarted);
require (!isFinalized);
// Sanity check the parameters
require (_paymentIdentifier != 0x0);
// Look up the payment identifier. We expect to find an empty Payment record.
Payment storage p = payments[_paymentIdentifier];
require(p.paymentAmount == 0);
require(p.status == 0 || p.status == 10);
p.paymentIdentifier = 0x0;
p.paymentHash = 0x0;
p.date = 0;
p.status = 0;
payments[_paymentIdentifier] = p;
PaymentExpectationCancelled(_paymentIdentifier);
}
// Submits a payment to the contract with the spcified payment identifier. If the contract is
// not expecting the specified payment, then the payment is held. Expected payemnts are automatically
// accepted and forwarded to the sales wallet.
function submitPayment(bytes8 _paymentIdentifier, uint32 nonce) payable {
require (saleStarted);
require (!isFinalized);
// Sanity Check the Parameters
require (_paymentIdentifier != 0x0);
Payment storage p = payments[_paymentIdentifier];
require (p.status == PENDING_STATUS);
require (p.from == 0x0);
require (p.paymentHash != 0x0);
require (msg.value > 0);
// Calculate the Payment Hash and insure it matches the expected hash
require (p.paymentHash == calculateHash(_paymentIdentifier, msg.value, nonce)) ;
bool forwardPayment = (p.status == PENDING_STATUS);
p.from = msg.sender;
p.paymentIdentifier = _paymentIdentifier;
p.date = now;
p.paymentAmount = msg.value;
p.status = PAID_STATUS;
payments[_paymentIdentifier] = p;
PaymentSubmitted (p.from, p.paymentIdentifier, p.paymentAmount);
if ( forwardPayment ) {
sendPaymentToWallet (p) ;
}
}
// Accepts a pending payment and forwards the payment amount to the sales wallet.
function acceptPayment(bytes8 _paymentIdentifier) onlyOwnerOrManager {
// Sanity Check the Parameters
require (_paymentIdentifier != 0x0);
Payment storage p = payments[_paymentIdentifier];
require (p.from != 0x0) ;
require (p.status == PAID_STATUS);
sendPaymentToWallet(p);
}
// Rejects a pending payment and returns the payment to the payer.
function rejectPayment(bytes8 _paymentIdentifier) onlyOwnerOrManager {
// Sanity Check the Parameters
require (_paymentIdentifier != 0x0);
Payment storage p = payments[_paymentIdentifier] ;
require (p.from != 0x0) ;
require (p.status == PAID_STATUS);
refundPayment(p) ;
}
// ******** Utility Methods ********
// Might be removed before deploying the Smart Contract Live.
// Returns the payment information for a particular payment identifier.
function verifyPayment(bytes8 _paymentIdentifier) constant onlyOwnerOrManager returns (address from, uint256 paymentAmount, uint date, bytes32 paymentHash, uint8 status) {
Payment storage payment = payments[_paymentIdentifier];
return (payment.from, payment.paymentAmount, payment.date, payment.paymentHash, payment.status);
}
// Kills this contract. Used only during debugging.
// TODO: Remove this method before deploying Smart Contract.
function kill() onlyOwner {
selfdestruct(msg.sender);
}
// ******** Internal Methods ********
// Internal function that transfers the ether sent with a payment on to the sales wallet.
function sendPaymentToWallet(Payment _payment) internal {
if ( salesWallet.send(_payment.paymentAmount) ) {
_payment.status = ACCEPTED_STATUS;
payments[_payment.paymentIdentifier] = _payment;
PaymentAccepted (_payment.from, _payment.paymentIdentifier, _payment.paymentAmount);
} else {
UnableToAcceptPayment (_payment.from, _payment.paymentIdentifier, _payment.paymentAmount);
}
}
// Internal function that transfers the ether sent with a payment back to the sender.
function refundPayment(Payment _payment) internal {
if ( _payment.from.send(_payment.paymentAmount) ) {
_payment.status = REJECTED_STATUS;
payments[_payment.paymentIdentifier] = _payment;
PaymentRejected (_payment.from, _payment.paymentIdentifier, _payment.paymentAmount);
} else {
UnableToRejectPayment (_payment.from, _payment.paymentIdentifier, _payment.paymentAmount);
}
}
// Calculates the hash for the provided payment information.
// TODO: Make this method internal before deploying Smart Contract.
function calculateHash(bytes8 _paymentIdentifier, uint256 _amount, uint32 _nonce) constant returns (bytes32 hash) {
return sha3(_paymentIdentifier, _amount, _nonce);
}
function finalization() internal {
saleStarted = false;
SaleClosed();
}
} | Kills this contract. Used only during debugging. TODO: Remove this method before deploying Smart Contract. | function kill() onlyOwner {
selfdestruct(msg.sender);
}
| 13,058,048 |
/**
*Submitted for verification at Etherscan.io on 2022-03-22
*/
/**
Memecoin made to raise awareness for the upcoming gay pride. Some of the taxes will go to
#lgbtq associations to fight against homophobia.
https://t.me/ApePridePortal/4
https://twitter.com/ApePride
Be proud & Ape Pride
*/
// SPDX-License-Identifier: MIT
pragma solidity =0.8.10 >=0.8.10 >=0.8.0 <0.9.0;
pragma experimental ABIEncoderV2;
////// lib/openzeppelin-contracts/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.0 (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;
}
}
////// lib/openzeppelin-contracts/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.0 (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);
}
}
////// lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts v4.4.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 `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);
}
////// lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// OpenZeppelin Contracts v4.4.0 (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);
}
////// lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol)
/* pragma solidity ^0.8.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 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 {}
}
////// lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.0 (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;
}
}
}
////// src/IUniswapV2Factory.sol
/* pragma solidity 0.8.10; */
/* pragma experimental ABIEncoderV2; */
interface IUniswapV2Factory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256
);
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(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
////// src/IUniswapV2Pair.sol
/* pragma solidity 0.8.10; */
/* pragma experimental ABIEncoderV2; */
interface IUniswapV2Pair {
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(address indexed from, address indexed to, uint256 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 (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 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 (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(
address indexed sender,
uint256 amount0,
uint256 amount1,
address indexed to
);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
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 (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to)
external
returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
////// src/IUniswapV2Router02.sol
/* pragma solidity 0.8.10; */
/* pragma experimental ABIEncoderV2; */
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
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 addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
////// src/freecain.sol
/* pragma solidity >=0.8.10; */
/* import {IUniswapV2Router02} from "./IUniswapV2Router02.sol"; */
/* import {IUniswapV2Factory} from "./IUniswapV2Factory.sol"; */
/* import {IUniswapV2Pair} from "./IUniswapV2Pair.sol"; */
/* import {IERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; */
/* import {ERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol"; */
/* import {Ownable} from "lib/openzeppelin-contracts/contracts/access/Ownable.sol"; */
/* import {SafeMath} from "lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol"; */
contract ApePride is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public marketingWallet;
address public cainWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 5;
bool public lpBurnEnabled = true;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyCainFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellCainFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForCain;
/******************/
// exlcude from fees and max transaction amount
mapping(address => bool) private _isExcludedFromFees;
mapping(address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping(address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(
address indexed newAddress,
address indexed oldAddress
);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event cainWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("Ape Pride", "ApePride") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 4;
uint256 _buyLiquidityFee = 3;
uint256 _buyCainFee = 3;
uint256 _sellMarketingFee = 5;
uint256 _sellLiquidityFee = 4;
uint256 _sellCainFee = 5;
uint256 totalSupply = 1_000_000_000 * 1e18;
maxTransactionAmount = 10_000_000 * 1e18; // 1% from total supply maxTransactionAmountTxn
maxWallet = 20_000_000 * 1e18; // 2% from total supply maxWallet
swapTokensAtAmount = (totalSupply * 5) / 10000; // 0.05% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyCainFee = _buyCainFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyCainFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellCainFee = _sellCainFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellCainFee;
marketingWallet = address(0x83918B6a05ddB267D1C38099f5b9A995102f6830); // set as marketing wallet
cainWallet = address(0x83918B6a05ddB267D1C38099f5b9A995102f6830); // set as cain wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool) {
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool) {
transferDelayEnabled = false;
return true;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount)
external
onlyOwner
returns (bool)
{
require(
newAmount >= (totalSupply() * 1) / 100000,
"Swap amount cannot be lower than 0.001% total supply."
);
require(
newAmount <= (totalSupply() * 5) / 1000,
"Swap amount cannot be higher than 0.5% total supply."
);
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 1) / 1000) / 1e18,
"Cannot set maxTransactionAmount lower than 0.1%"
);
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 5) / 1000) / 1e18,
"Cannot set maxWallet lower than 0.5%"
);
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx)
public
onlyOwner
{
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner {
swapEnabled = enabled;
}
function updateBuyFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _cainFee
) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyCainFee = _cainFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyCainFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _cainFee
) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellCainFee = _cainFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellCainFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value)
public
onlyOwner
{
require(
pair != uniswapV2Pair,
"The pair cannot be removed from automatedMarketMakerPairs"
);
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet)
external
onlyOwner
{
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateCainWallet(address newWallet) external onlyOwner {
emit cainWalletUpdated(newWallet, cainWallet);
cainWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns (bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
//when sell
else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
} else if (!_isExcludedMaxTransactionAmount[to]) {
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if (takeFee) {
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForCain += (fees * sellCainFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
// on buy
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForCain += (fees * buyCainFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
deadAddress,
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForCain;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = (contractBalance * tokensForLiquidity) /
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethForCain = ethBalance.mul(tokensForCain).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForCain;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForCain = 0;
(success, ) = address(cainWallet).call{value: ethForCain}("");
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(marketingWallet).call{
value: address(this).balance
}("");
}
function setAutoLPBurnSettings(
uint256 _frequencyInSeconds,
uint256 _percent,
bool _Enabled
) external onlyOwner {
require(
_frequencyInSeconds >= 600,
"cannot set buyback more often than every 10 minutes"
);
require(
_percent <= 1000 && _percent >= 0,
"Must set auto LP burn percent between 0% and 10%"
);
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool) {
lastLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(
10000
);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent)
external
onlyOwner
returns (bool)
{
require(
block.timestamp > lastManualLpBurnTime + manualBurnFrequency,
"Must wait for cooldown to finish"
);
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
} | exclude from paying fees or having max transaction amount | constructor() ERC20("Ape Pride", "ApePride") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 4;
uint256 _buyLiquidityFee = 3;
uint256 _buyCainFee = 3;
uint256 _sellMarketingFee = 5;
uint256 _sellLiquidityFee = 4;
uint256 _sellCainFee = 5;
uint256 totalSupply = 1_000_000_000 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyCainFee = _buyCainFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyCainFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellCainFee = _sellCainFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellCainFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 816 |
//Address: 0x10a5f6dbd1f9e56fe09df25b1163cd299d5d2413
//Contract name: EthernautsExplore
//Balance: 0.251 Ether
//Verification Date: 4/24/2018
//Transacion Count: 727
// CODE STARTS HERE
pragma solidity ^0.4.19;
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Ethernauts
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
function takeOwnership(uint256 _tokenId) public;
function implementsERC721() public pure returns (bool);
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
// Extend this library for child contracts
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;
}
/**
* @dev Compara two numbers, and return the bigger one.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
if (a > b) {
return a;
} else {
return b;
}
}
/**
* @dev Compara two numbers, and return the bigger one.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
if (a < b) {
return a;
} else {
return b;
}
}
}
/// @dev Base contract for all Ethernauts contracts holding global constants and functions.
contract EthernautsBase {
/*** CONSTANTS USED ACROSS CONTRACTS ***/
/// @dev Used by all contracts that interfaces with Ethernauts
/// The ERC-165 interface signature for ERC-721.
/// Ref: https://github.com/ethereum/EIPs/issues/165
/// Ref: https://github.com/ethereum/EIPs/issues/721
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('takeOwnership(uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
/// @dev due solidity limitation we cannot return dynamic array from methods
/// so it creates incompability between functions across different contracts
uint8 public constant STATS_SIZE = 10;
uint8 public constant SHIP_SLOTS = 5;
// Possible state of any asset
enum AssetState { Available, UpForLease, Used }
// Possible state of any asset
// NotValid is to avoid 0 in places where category must be bigger than zero
enum AssetCategory { NotValid, Sector, Manufacturer, Ship, Object, Factory, CrewMember }
/// @dev Sector stats
enum ShipStats {Level, Attack, Defense, Speed, Range, Luck}
/// @notice Possible attributes for each asset
/// 00000001 - Seeded - Offered to the economy by us, the developers. Potentially at regular intervals.
/// 00000010 - Producible - Product of a factory and/or factory contract.
/// 00000100 - Explorable- Product of exploration.
/// 00001000 - Leasable - Can be rented to other users and will return to the original owner once the action is complete.
/// 00010000 - Permanent - Cannot be removed, always owned by a user.
/// 00100000 - Consumable - Destroyed after N exploration expeditions.
/// 01000000 - Tradable - Buyable and sellable on the market.
/// 10000000 - Hot Potato - Automatically gets put up for sale after acquiring.
bytes2 public ATTR_SEEDED = bytes2(2**0);
bytes2 public ATTR_PRODUCIBLE = bytes2(2**1);
bytes2 public ATTR_EXPLORABLE = bytes2(2**2);
bytes2 public ATTR_LEASABLE = bytes2(2**3);
bytes2 public ATTR_PERMANENT = bytes2(2**4);
bytes2 public ATTR_CONSUMABLE = bytes2(2**5);
bytes2 public ATTR_TRADABLE = bytes2(2**6);
bytes2 public ATTR_GOLDENGOOSE = bytes2(2**7);
}
/// @notice This contract manages the various addresses and constraints for operations
// that can be executed only by specific roles. Namely CEO and CTO. it also includes pausable pattern.
contract EthernautsAccessControl is EthernautsBase {
// This facet controls access control for Ethernauts.
// All roles have same responsibilities and rights, but there is slight differences between them:
//
// - The CEO: The CEO can reassign other roles and only role that can unpause the smart contract.
// It is initially set to the address that created the smart contract.
//
// - The CTO: The CTO can change contract address, oracle address and plan for upgrades.
//
// - The COO: The COO can change contract address and add create assets.
//
/// @dev Emited when contract is upgraded - See README.md for updgrade plan
/// @param newContract address pointing to new contract
event ContractUpgrade(address newContract);
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public ctoAddress;
address public cooAddress;
address public oracleAddress;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CTO-only functionality
modifier onlyCTO() {
require(msg.sender == ctoAddress);
_;
}
/// @dev Access modifier for CTO-only functionality
modifier onlyOracle() {
require(msg.sender == oracleAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == ceoAddress ||
msg.sender == ctoAddress ||
msg.sender == cooAddress
);
_;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the CTO. Only available to the current CTO or CEO.
/// @param _newCTO The address of the new CTO
function setCTO(address _newCTO) external {
require(
msg.sender == ceoAddress ||
msg.sender == ctoAddress
);
require(_newCTO != address(0));
ctoAddress = _newCTO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current COO or CEO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) external {
require(
msg.sender == ceoAddress ||
msg.sender == cooAddress
);
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/// @dev Assigns a new address to act as oracle.
/// @param _newOracle The address of oracle
function setOracle(address _newOracle) external {
require(msg.sender == ctoAddress);
require(_newOracle != address(0));
oracleAddress = _newOracle;
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CTO account is compromised.
/// @notice This is public rather than external so it can be called by
/// derived contracts.
function unpause() public onlyCEO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
/// @title Storage contract for Ethernauts Data. Common structs and constants.
/// @notice This is our main data storage, constants and data types, plus
// internal functions for managing the assets. It is isolated and only interface with
// a list of granted contracts defined by CTO
/// @author Ethernauts - Fernando Pauer
contract EthernautsStorage is EthernautsAccessControl {
function EthernautsStorage() public {
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
// the creator of the contract is the initial CTO as well
ctoAddress = msg.sender;
// the creator of the contract is the initial CTO as well
cooAddress = msg.sender;
// the creator of the contract is the initial Oracle as well
oracleAddress = msg.sender;
}
/// @notice No tipping!
/// @dev Reject all Ether from being sent here. Hopefully, we can prevent user accidents.
function() external payable {
require(msg.sender == address(this));
}
/*** Mapping for Contracts with granted permission ***/
mapping (address => bool) public contractsGrantedAccess;
/// @dev grant access for a contract to interact with this contract.
/// @param _v2Address The contract address to grant access
function grantAccess(address _v2Address) public onlyCTO {
// See README.md for updgrade plan
contractsGrantedAccess[_v2Address] = true;
}
/// @dev remove access from a contract to interact with this contract.
/// @param _v2Address The contract address to be removed
function removeAccess(address _v2Address) public onlyCTO {
// See README.md for updgrade plan
delete contractsGrantedAccess[_v2Address];
}
/// @dev Only allow permitted contracts to interact with this contract
modifier onlyGrantedContracts() {
require(contractsGrantedAccess[msg.sender] == true);
_;
}
modifier validAsset(uint256 _tokenId) {
require(assets[_tokenId].ID > 0);
_;
}
/*** DATA TYPES ***/
/// @dev The main Ethernauts asset struct. Every asset in Ethernauts is represented by a copy
/// of this structure. Note that the order of the members in this structure
/// is important because of the byte-packing rules used by Ethereum.
/// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html
struct Asset {
// Asset ID is a identifier for look and feel in frontend
uint16 ID;
// Category = Sectors, Manufacturers, Ships, Objects (Upgrades/Misc), Factories and CrewMembers
uint8 category;
// The State of an asset: Available, On sale, Up for lease, Cooldown, Exploring
uint8 state;
// Attributes
// byte pos - Definition
// 00000001 - Seeded - Offered to the economy by us, the developers. Potentially at regular intervals.
// 00000010 - Producible - Product of a factory and/or factory contract.
// 00000100 - Explorable- Product of exploration.
// 00001000 - Leasable - Can be rented to other users and will return to the original owner once the action is complete.
// 00010000 - Permanent - Cannot be removed, always owned by a user.
// 00100000 - Consumable - Destroyed after N exploration expeditions.
// 01000000 - Tradable - Buyable and sellable on the market.
// 10000000 - Hot Potato - Automatically gets put up for sale after acquiring.
bytes2 attributes;
// The timestamp from the block when this asset was created.
uint64 createdAt;
// The minimum timestamp after which this asset can engage in exploring activities again.
uint64 cooldownEndBlock;
// The Asset's stats can be upgraded or changed based on exploration conditions.
// It will be defined per child contract, but all stats have a range from 0 to 255
// Examples
// 0 = Ship Level
// 1 = Ship Attack
uint8[STATS_SIZE] stats;
// Set to the cooldown time that represents exploration duration for this asset.
// Defined by a successful exploration action, regardless of whether this asset is acting as ship or a part.
uint256 cooldown;
// a reference to a super asset that manufactured the asset
uint256 builtBy;
}
/*** CONSTANTS ***/
// @dev Sanity check that allows us to ensure that we are pointing to the
// right storage contract in our EthernautsLogic(address _CStorageAddress) call.
bool public isEthernautsStorage = true;
/*** STORAGE ***/
/// @dev An array containing the Asset struct for all assets in existence. The Asset UniqueId
/// of each asset is actually an index into this array.
Asset[] public assets;
/// @dev A mapping from Asset UniqueIDs to the price of the token.
/// stored outside Asset Struct to save gas, because price can change frequently
mapping (uint256 => uint256) internal assetIndexToPrice;
/// @dev A mapping from asset UniqueIDs to the address that owns them. All assets have some valid owner address.
mapping (uint256 => address) internal assetIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) internal ownershipTokenCount;
/// @dev A mapping from AssetUniqueIDs to an address that has been approved to call
/// transferFrom(). Each Asset can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) internal assetIndexToApproved;
/*** SETTERS ***/
/// @dev set new asset price
/// @param _tokenId asset UniqueId
/// @param _price asset price
function setPrice(uint256 _tokenId, uint256 _price) public onlyGrantedContracts {
assetIndexToPrice[_tokenId] = _price;
}
/// @dev Mark transfer as approved
/// @param _tokenId asset UniqueId
/// @param _approved address approved
function approve(uint256 _tokenId, address _approved) public onlyGrantedContracts {
assetIndexToApproved[_tokenId] = _approved;
}
/// @dev Assigns ownership of a specific Asset to an address.
/// @param _from current owner address
/// @param _to new owner address
/// @param _tokenId asset UniqueId
function transfer(address _from, address _to, uint256 _tokenId) public onlyGrantedContracts {
// Since the number of assets is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
// transfer ownership
assetIndexToOwner[_tokenId] = _to;
// When creating new assets _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete assetIndexToApproved[_tokenId];
}
}
/// @dev A public method that creates a new asset and stores it. This
/// method does basic checking and should only be called from other contract when the
/// input data is known to be valid. Will NOT generate any event it is delegate to business logic contracts.
/// @param _creatorTokenID The asset who is father of this asset
/// @param _owner First owner of this asset
/// @param _price asset price
/// @param _ID asset ID
/// @param _category see Asset Struct description
/// @param _state see Asset Struct description
/// @param _attributes see Asset Struct description
/// @param _stats see Asset Struct description
function createAsset(
uint256 _creatorTokenID,
address _owner,
uint256 _price,
uint16 _ID,
uint8 _category,
uint8 _state,
uint8 _attributes,
uint8[STATS_SIZE] _stats,
uint256 _cooldown,
uint64 _cooldownEndBlock
)
public onlyGrantedContracts
returns (uint256)
{
// Ensure our data structures are always valid.
require(_ID > 0);
require(_category > 0);
require(_attributes != 0x0);
require(_stats.length > 0);
Asset memory asset = Asset({
ID: _ID,
category: _category,
builtBy: _creatorTokenID,
attributes: bytes2(_attributes),
stats: _stats,
state: _state,
createdAt: uint64(now),
cooldownEndBlock: _cooldownEndBlock,
cooldown: _cooldown
});
uint256 newAssetUniqueId = assets.push(asset) - 1;
// Check it reached 4 billion assets but let's just be 100% sure.
require(newAssetUniqueId == uint256(uint32(newAssetUniqueId)));
// store price
assetIndexToPrice[newAssetUniqueId] = _price;
// This will assign ownership
transfer(address(0), _owner, newAssetUniqueId);
return newAssetUniqueId;
}
/// @dev A public method that edit asset in case of any mistake is done during process of creation by the developer. This
/// This method doesn't do any checking and should only be called when the
/// input data is known to be valid.
/// @param _tokenId The token ID
/// @param _creatorTokenID The asset that create that token
/// @param _price asset price
/// @param _ID asset ID
/// @param _category see Asset Struct description
/// @param _state see Asset Struct description
/// @param _attributes see Asset Struct description
/// @param _stats see Asset Struct description
/// @param _cooldown asset cooldown index
function editAsset(
uint256 _tokenId,
uint256 _creatorTokenID,
uint256 _price,
uint16 _ID,
uint8 _category,
uint8 _state,
uint8 _attributes,
uint8[STATS_SIZE] _stats,
uint16 _cooldown
)
external validAsset(_tokenId) onlyCLevel
returns (uint256)
{
// Ensure our data structures are always valid.
require(_ID > 0);
require(_category > 0);
require(_attributes != 0x0);
require(_stats.length > 0);
// store price
assetIndexToPrice[_tokenId] = _price;
Asset storage asset = assets[_tokenId];
asset.ID = _ID;
asset.category = _category;
asset.builtBy = _creatorTokenID;
asset.attributes = bytes2(_attributes);
asset.stats = _stats;
asset.state = _state;
asset.cooldown = _cooldown;
}
/// @dev Update only stats
/// @param _tokenId asset UniqueId
/// @param _stats asset state, see Asset Struct description
function updateStats(uint256 _tokenId, uint8[STATS_SIZE] _stats) public validAsset(_tokenId) onlyGrantedContracts {
assets[_tokenId].stats = _stats;
}
/// @dev Update only asset state
/// @param _tokenId asset UniqueId
/// @param _state asset state, see Asset Struct description
function updateState(uint256 _tokenId, uint8 _state) public validAsset(_tokenId) onlyGrantedContracts {
assets[_tokenId].state = _state;
}
/// @dev Update Cooldown for a single asset
/// @param _tokenId asset UniqueId
/// @param _cooldown asset state, see Asset Struct description
function setAssetCooldown(uint256 _tokenId, uint256 _cooldown, uint64 _cooldownEndBlock)
public validAsset(_tokenId) onlyGrantedContracts {
assets[_tokenId].cooldown = _cooldown;
assets[_tokenId].cooldownEndBlock = _cooldownEndBlock;
}
/*** GETTERS ***/
/// @notice Returns only stats data about a specific asset.
/// @dev it is necessary due solidity compiler limitations
/// when we have large qty of parameters it throws StackTooDeepException
/// @param _tokenId The UniqueId of the asset of interest.
function getStats(uint256 _tokenId) public view returns (uint8[STATS_SIZE]) {
return assets[_tokenId].stats;
}
/// @dev return current price of an asset
/// @param _tokenId asset UniqueId
function priceOf(uint256 _tokenId) public view returns (uint256 price) {
return assetIndexToPrice[_tokenId];
}
/// @notice Check if asset has all attributes passed by parameter
/// @param _tokenId The UniqueId of the asset of interest.
/// @param _attributes see Asset Struct description
function hasAllAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) {
return assets[_tokenId].attributes & _attributes == _attributes;
}
/// @notice Check if asset has any attribute passed by parameter
/// @param _tokenId The UniqueId of the asset of interest.
/// @param _attributes see Asset Struct description
function hasAnyAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) {
return assets[_tokenId].attributes & _attributes != 0x0;
}
/// @notice Check if asset is in the state passed by parameter
/// @param _tokenId The UniqueId of the asset of interest.
/// @param _category see AssetCategory in EthernautsBase for possible states
function isCategory(uint256 _tokenId, uint8 _category) public view returns (bool) {
return assets[_tokenId].category == _category;
}
/// @notice Check if asset is in the state passed by parameter
/// @param _tokenId The UniqueId of the asset of interest.
/// @param _state see enum AssetState in EthernautsBase for possible states
function isState(uint256 _tokenId, uint8 _state) public view returns (bool) {
return assets[_tokenId].state == _state;
}
/// @notice Returns owner of a given Asset(Token).
/// @dev Required for ERC-721 compliance.
/// @param _tokenId asset UniqueId
function ownerOf(uint256 _tokenId) public view returns (address owner)
{
return assetIndexToOwner[_tokenId];
}
/// @dev Required for ERC-721 compliance
/// @notice Returns the number of Assets owned by a specific address.
/// @param _owner The owner address to check.
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @dev Checks if a given address currently has transferApproval for a particular Asset.
/// @param _tokenId asset UniqueId
function approvedFor(uint256 _tokenId) public view onlyGrantedContracts returns (address) {
return assetIndexToApproved[_tokenId];
}
/// @notice Returns the total number of Assets currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint256) {
return assets.length;
}
/// @notice List all existing tokens. It can be filtered by attributes or assets with owner
/// @param _owner filter all assets by owner
function getTokenList(address _owner, uint8 _withAttributes, uint256 start, uint256 count) external view returns(
uint256[6][]
) {
uint256 totalAssets = assets.length;
if (totalAssets == 0) {
// Return an empty array
return new uint256[6][](0);
} else {
uint256[6][] memory result = new uint256[6][](totalAssets > count ? count : totalAssets);
uint256 resultIndex = 0;
bytes2 hasAttributes = bytes2(_withAttributes);
Asset memory asset;
for (uint256 tokenId = start; tokenId < totalAssets && resultIndex < count; tokenId++) {
asset = assets[tokenId];
if (
(asset.state != uint8(AssetState.Used)) &&
(assetIndexToOwner[tokenId] == _owner || _owner == address(0)) &&
(asset.attributes & hasAttributes == hasAttributes)
) {
result[resultIndex][0] = tokenId;
result[resultIndex][1] = asset.ID;
result[resultIndex][2] = asset.category;
result[resultIndex][3] = uint256(asset.attributes);
result[resultIndex][4] = asset.cooldown;
result[resultIndex][5] = assetIndexToPrice[tokenId];
resultIndex++;
}
}
return result;
}
}
}
/// @title The facet of the Ethernauts contract that manages ownership, ERC-721 compliant.
/// @notice This provides the methods required for basic non-fungible token
// transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721).
// It interfaces with EthernautsStorage provinding basic functions as create and list, also holds
// reference to logic contracts as Auction, Explore and so on
/// @author Ethernatus - Fernando Pauer
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
contract EthernautsOwnership is EthernautsAccessControl, ERC721 {
/// @dev Contract holding only data.
EthernautsStorage public ethernautsStorage;
/*** CONSTANTS ***/
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "Ethernauts";
string public constant symbol = "ETNT";
/********* ERC 721 - COMPLIANCE CONSTANTS AND FUNCTIONS ***************/
/**********************************************************************/
bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)'));
/*** EVENTS ***/
// Events as per ERC-721
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed owner, address indexed approved, uint256 tokens);
/// @dev When a new asset is create it emits build event
/// @param owner The address of asset owner
/// @param tokenId Asset UniqueID
/// @param assetId ID that defines asset look and feel
/// @param price asset price
event Build(address owner, uint256 tokenId, uint16 assetId, uint256 price);
function implementsERC721() public pure returns (bool) {
return true;
}
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. ERC-165 and ERC-721.
/// @param _interfaceID interface signature ID
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/// @dev Checks if a given address is the current owner of a particular Asset.
/// @param _claimant the address we are validating against.
/// @param _tokenId asset UniqueId, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return ethernautsStorage.ownerOf(_tokenId) == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular Asset.
/// @param _claimant the address we are confirming asset is approved for.
/// @param _tokenId asset UniqueId, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return ethernautsStorage.approvedFor(_tokenId) == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting Assets on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
ethernautsStorage.approve(_tokenId, _approved);
}
/// @notice Returns the number of Assets owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ethernautsStorage.balanceOf(_owner);
}
/// @dev Required for ERC-721 compliance.
/// @notice Transfers a Asset to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// Ethernauts specifically) or your Asset may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Asset to transfer.
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any assets
// (except very briefly after it is created and before it goes on auction).
require(_to != address(this));
// Disallow transfers to the storage contract to prevent accidental
// misuse. Auction or Upgrade contracts should only take ownership of assets
// through the allow + transferFrom flow.
require(_to != address(ethernautsStorage));
// You can only send your own asset.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
ethernautsStorage.transfer(msg.sender, _to, _tokenId);
}
/// @dev Required for ERC-721 compliance.
/// @notice Grant another address the right to transfer a specific Asset via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Asset that can be transferred if this call succeeds.
function approve(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Asset owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Asset to be transferred.
/// @param _to The address that should take ownership of the Asset. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Asset to be transferred.
function _transferFrom(
address _from,
address _to,
uint256 _tokenId
)
internal
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any assets (except for used assets).
require(_owns(_from, _tokenId));
// Check for approval and valid ownership
require(_approvedFor(_to, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
ethernautsStorage.transfer(_from, _to, _tokenId);
}
/// @dev Required for ERC-721 compliance.
/// @notice Transfer a Asset owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Asset to be transfered.
/// @param _to The address that should take ownership of the Asset. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Asset to be transferred.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
_transferFrom(_from, _to, _tokenId);
}
/// @dev Required for ERC-721 compliance.
/// @notice Allow pre-approved user to take ownership of a token
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
function takeOwnership(uint256 _tokenId) public {
address _from = ethernautsStorage.ownerOf(_tokenId);
// Safety check to prevent against an unexpected 0x0 default.
require(_from != address(0));
_transferFrom(_from, msg.sender, _tokenId);
}
/// @notice Returns the total number of Assets currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint256) {
return ethernautsStorage.totalSupply();
}
/// @notice Returns owner of a given Asset(Token).
/// @param _tokenId Token ID to get owner.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = ethernautsStorage.ownerOf(_tokenId);
require(owner != address(0));
}
/// @dev Creates a new Asset with the given fields. ONly available for C Levels
/// @param _creatorTokenID The asset who is father of this asset
/// @param _price asset price
/// @param _assetID asset ID
/// @param _category see Asset Struct description
/// @param _attributes see Asset Struct description
/// @param _stats see Asset Struct description
function createNewAsset(
uint256 _creatorTokenID,
address _owner,
uint256 _price,
uint16 _assetID,
uint8 _category,
uint8 _attributes,
uint8[STATS_SIZE] _stats
)
external onlyCLevel
returns (uint256)
{
// owner must be sender
require(_owner != address(0));
uint256 tokenID = ethernautsStorage.createAsset(
_creatorTokenID,
_owner,
_price,
_assetID,
_category,
uint8(AssetState.Available),
_attributes,
_stats,
0,
0
);
// emit the build event
Build(
_owner,
tokenID,
_assetID,
_price
);
return tokenID;
}
/// @notice verify if token is in exploration time
/// @param _tokenId The Token ID that can be upgraded
function isExploring(uint256 _tokenId) public view returns (bool) {
uint256 cooldown;
uint64 cooldownEndBlock;
(,,,,,cooldownEndBlock, cooldown,) = ethernautsStorage.assets(_tokenId);
return (cooldown > now) || (cooldownEndBlock > uint64(block.number));
}
}
/// @title The facet of the Ethernauts Logic contract handle all common code for logic/business contracts
/// @author Ethernatus - Fernando Pauer
contract EthernautsLogic is EthernautsOwnership {
// Set in case the logic contract is broken and an upgrade is required
address public newContractAddress;
/// @dev Constructor
function EthernautsLogic() public {
// the creator of the contract is the initial CEO, COO, CTO
ceoAddress = msg.sender;
ctoAddress = msg.sender;
cooAddress = msg.sender;
oracleAddress = msg.sender;
// Starts paused.
paused = true;
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) external onlyCTO whenPaused {
// See README.md for updgrade plan
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
/// @dev set a new reference to the NFT ownership contract
/// @param _CStorageAddress - address of a deployed contract implementing EthernautsStorage.
function setEthernautsStorageContract(address _CStorageAddress) public onlyCLevel whenPaused {
EthernautsStorage candidateContract = EthernautsStorage(_CStorageAddress);
require(candidateContract.isEthernautsStorage());
ethernautsStorage = candidateContract;
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
/// @notice This is public rather than external so we can call super.unpause
/// without using an expensive CALL.
function unpause() public onlyCEO whenPaused {
require(ethernautsStorage != address(0));
require(newContractAddress == address(0));
// require this contract to have access to storage contract
require(ethernautsStorage.contractsGrantedAccess(address(this)) == true);
// Actually unpause the contract.
super.unpause();
}
// @dev Allows the COO to capture the balance available to the contract.
function withdrawBalances(address _to) public onlyCLevel {
_to.transfer(this.balance);
}
/// return current contract balance
function getBalance() public view onlyCLevel returns (uint256) {
return this.balance;
}
}
/// @title The facet of the Ethernauts Explore contract that send a ship to explore the deep space.
/// @notice An owned ship can be send on an expedition. Exploration takes time
// and will always result in “success”. This means the ship can never be destroyed
// and always returns with a collection of loot. The degree of success is dependent
// on different factors as sector stats, gamma ray burst number and ship stats.
// While the ship is exploring it cannot be acted on in any way until the expedition completes.
// After the ship returns from an expedition the user is then rewarded with a number of objects (assets).
/// @author Ethernatus - Fernando Pauer
contract EthernautsExplore is EthernautsLogic {
/// @dev Delegate constructor to Nonfungible contract.
function EthernautsExplore() public
EthernautsLogic() {}
/*** EVENTS ***/
/// emit signal to anyone listening in the universe
event Explore(uint256 shipId, uint256 sectorID, uint256 crewId, uint256 time);
event Result(uint256 shipId, uint256 sectorID);
/*** CONSTANTS ***/
uint8 constant STATS_CAPOUT = 2**8 - 1; // all stats have a range from 0 to 255
// @dev Sanity check that allows us to ensure that we are pointing to the
// right explore contract in our EthernautsCrewMember(address _CExploreAddress) call.
bool public isEthernautsExplore = true;
// An approximation of currently how many seconds are in between blocks.
uint256 public secondsPerBlock = 15;
uint256 public TICK_TIME = 15; // time is always in minutes
// exploration fee
uint256 public percentageCut = 90;
int256 public SPEED_STAT_MAX = 30;
int256 public RANGE_STAT_MAX = 20;
int256 public MIN_TIME_EXPLORE = 60;
int256 public MAX_TIME_EXPLORE = 2160;
int256 public RANGE_SCALE = 2;
/// @dev Sector stats
enum SectorStats {Size, Threat, Difficulty, Slots}
/// @dev hold all ships in exploration
uint256[] explorers;
/// @dev A mapping from Ship token to the exploration index.
mapping (uint256 => uint256) public tokenIndexToExplore;
/// @dev A mapping from Asset UniqueIDs to the sector token id.
mapping (uint256 => uint256) public tokenIndexToSector;
/// @dev A mapping from exploration index to the crew token id.
mapping (uint256 => uint256) public exploreIndexToCrew;
/// @dev A mission counter for crew.
mapping (uint256 => uint16) public missions;
/// @dev A mapping from Owner Cut (wei) to the sector token id.
mapping (uint256 => uint256) public sectorToOwnerCut;
mapping (uint256 => uint256) public sectorToOracleFee;
/// @dev Get a list of ship exploring our universe
function getExplorerList() public view returns(
uint256[3][]
) {
uint256[3][] memory tokens = new uint256[3][](50);
uint256 index = 0;
for(uint256 i = 0; i < explorers.length && index < 50; i++) {
if (explorers[i] > 0) {
tokens[index][0] = explorers[i];
tokens[index][1] = tokenIndexToSector[explorers[i]];
tokens[index][2] = exploreIndexToCrew[i];
index++;
}
}
if (index == 0) {
// Return an empty array
return new uint256[3][](0);
} else {
return tokens;
}
}
/// @dev Get a list of ship exploring our universe
/// @param _shipTokenId The Token ID that represents a ship
function getIndexByShip(uint256 _shipTokenId) public view returns( uint256 ) {
for(uint256 i = 0; i < explorers.length; i++) {
if (explorers[i] == _shipTokenId) {
return i;
}
}
return 0;
}
function setOwnerCut(uint256 _sectorId, uint256 _ownerCut) external onlyCLevel {
sectorToOwnerCut[_sectorId] = _ownerCut;
}
function setOracleFee(uint256 _sectorId, uint256 _oracleFee) external onlyCLevel {
sectorToOracleFee[_sectorId] = _oracleFee;
}
function setTickTime(uint256 _tickTime) external onlyCLevel {
TICK_TIME = _tickTime;
}
function setPercentageCut(uint256 _percentageCut) external onlyCLevel {
percentageCut = _percentageCut;
}
function setMissions(uint256 _tokenId, uint16 _total) public onlyCLevel {
missions[_tokenId] = _total;
}
/// @notice Explore a sector with a defined ship. Sectors contain a list of Objects that can be given to the players
/// when exploring. Each entry has a Drop Rate and are sorted by Sector ID and Drop rate.
/// The drop rate is a whole number between 0 and 1,000,000. 0 is 0% and 1,000,000 is 100%.
/// Every time a Sector is explored a random number between 0 and 1,000,000 is calculated for each available Object.
/// If the final result is lower than the Drop Rate of the Object, that Object will be rewarded to the player once
/// Exploration is complete. Only 1 to 5 Objects maximum can be dropped during one exploration.
/// (FUTURE VERSIONS) The final number will be affected by the user’s Ship Stats.
/// @param _shipTokenId The Token ID that represents a ship
/// @param _sectorTokenId The Token ID that represents a sector
/// @param _crewTokenId The Token ID that represents a crew
function explore(uint256 _shipTokenId, uint256 _sectorTokenId, uint256 _crewTokenId) payable external whenNotPaused {
// charge a fee for each exploration when the results are ready
require(msg.value >= sectorToOwnerCut[_sectorTokenId]);
// check if Asset is a ship or not
require(ethernautsStorage.isCategory(_shipTokenId, uint8(AssetCategory.Ship)));
// check if _sectorTokenId is a sector or not
require(ethernautsStorage.isCategory(_sectorTokenId, uint8(AssetCategory.Sector)));
// Ensure the Ship is in available state, otherwise it cannot explore
require(ethernautsStorage.isState(_shipTokenId, uint8(AssetState.Available)));
// ship could not be in exploration
require(tokenIndexToExplore[_shipTokenId] == 0);
require(!isExploring(_shipTokenId));
// check if explorer is ship owner
require(msg.sender == ethernautsStorage.ownerOf(_shipTokenId));
// check if owner sector is not empty
address sectorOwner = ethernautsStorage.ownerOf(_sectorTokenId);
// check if there is a crew and validating crew member
if (_crewTokenId > 0) {
// crew member should not be in exploration
require(!isExploring(_crewTokenId));
// check if Asset is a crew or not
require(ethernautsStorage.isCategory(_crewTokenId, uint8(AssetCategory.CrewMember)));
// check if crew member is same owner
require(msg.sender == ethernautsStorage.ownerOf(_crewTokenId));
}
/// store exploration data
tokenIndexToExplore[_shipTokenId] = explorers.push(_shipTokenId) - 1;
tokenIndexToSector[_shipTokenId] = _sectorTokenId;
uint8[STATS_SIZE] memory _shipStats = ethernautsStorage.getStats(_shipTokenId);
uint8[STATS_SIZE] memory _sectorStats = ethernautsStorage.getStats(_sectorTokenId);
// check if there is a crew and store data and change ship stats
if (_crewTokenId > 0) {
/// store crew exploration data
exploreIndexToCrew[tokenIndexToExplore[_shipTokenId]] = _crewTokenId;
missions[_crewTokenId]++;
//// grab crew stats and merge with ship
uint8[STATS_SIZE] memory _crewStats = ethernautsStorage.getStats(_crewTokenId);
_shipStats[uint256(ShipStats.Range)] += _crewStats[uint256(ShipStats.Range)];
_shipStats[uint256(ShipStats.Speed)] += _crewStats[uint256(ShipStats.Speed)];
if (_shipStats[uint256(ShipStats.Range)] > STATS_CAPOUT) {
_shipStats[uint256(ShipStats.Range)] = STATS_CAPOUT;
}
if (_shipStats[uint256(ShipStats.Speed)] > STATS_CAPOUT) {
_shipStats[uint256(ShipStats.Speed)] = STATS_CAPOUT;
}
}
/// set exploration time
uint256 time = uint256(_explorationTime(
_shipStats[uint256(ShipStats.Range)],
_shipStats[uint256(ShipStats.Speed)],
_sectorStats[uint256(SectorStats.Size)]
));
// exploration time in minutes converted to seconds
time *= 60;
uint64 _cooldownEndBlock = uint64((time/secondsPerBlock) + block.number);
ethernautsStorage.setAssetCooldown(_shipTokenId, now + time, _cooldownEndBlock);
// check if there is a crew store data and set crew exploration time
if (_crewTokenId > 0) {
/// store crew exploration time
ethernautsStorage.setAssetCooldown(_crewTokenId, now + time, _cooldownEndBlock);
}
// to avoid mistakes and charge unnecessary extra fees
uint256 feeExcess = SafeMath.sub(msg.value, sectorToOwnerCut[_sectorTokenId]);
uint256 payment = uint256(SafeMath.div(SafeMath.mul(msg.value, percentageCut), 100)) - sectorToOracleFee[_sectorTokenId];
/// emit signal to anyone listening in the universe
Explore(_shipTokenId, _sectorTokenId, _crewTokenId, now + time);
// keeping oracle accounts with balance
oracleAddress.transfer(sectorToOracleFee[_sectorTokenId]);
// paying sector owner
sectorOwner.transfer(payment);
// send excess back to explorer
msg.sender.transfer(feeExcess);
}
/// @notice Exploration is complete and at most 10 Objects will return during one exploration.
/// @param _shipTokenId The Token ID that represents a ship and can explore
/// @param _sectorTokenId The Token ID that represents a sector and can be explored
/// @param _IDs that represents a object returned from exploration
/// @param _attributes that represents attributes for each object returned from exploration
/// @param _stats that represents all stats for each object returned from exploration
function explorationResults(
uint256 _shipTokenId,
uint256 _sectorTokenId,
uint16[10] _IDs,
uint8[10] _attributes,
uint8[STATS_SIZE][10] _stats
)
external onlyOracle
{
uint256 cooldown;
uint64 cooldownEndBlock;
uint256 builtBy;
(,,,,,cooldownEndBlock, cooldown, builtBy) = ethernautsStorage.assets(_shipTokenId);
address owner = ethernautsStorage.ownerOf(_shipTokenId);
require(owner != address(0));
/// create objects returned from exploration
uint256 i = 0;
for (i = 0; i < 10 && _IDs[i] > 0; i++) {
_buildAsset(
_sectorTokenId,
owner,
0,
_IDs[i],
uint8(AssetCategory.Object),
uint8(_attributes[i]),
_stats[i],
cooldown,
cooldownEndBlock
);
}
// to guarantee at least 1 result per exploration
require(i > 0);
/// remove from explore list
explorers[tokenIndexToExplore[_shipTokenId]] = 0;
delete tokenIndexToExplore[_shipTokenId];
delete tokenIndexToSector[_shipTokenId];
/// emit signal to anyone listening in the universe
Result(_shipTokenId, _sectorTokenId);
}
/// @notice Cancel ship exploration in case it get stuck
/// @param _shipTokenId The Token ID that represents a ship and can explore
function cancelExplorationByShip(
uint256 _shipTokenId
)
external onlyCLevel
{
uint256 index = tokenIndexToExplore[_shipTokenId];
if (index > 0) {
/// remove from explore list
explorers[index] = 0;
if (exploreIndexToCrew[index] > 0) {
delete exploreIndexToCrew[index];
}
}
delete tokenIndexToExplore[_shipTokenId];
delete tokenIndexToSector[_shipTokenId];
}
/// @notice Cancel exploration in case it get stuck
/// @param _index The exploration position that represents a exploring ship
function cancelExplorationByIndex(
uint256 _index
)
external onlyCLevel
{
uint256 shipId = explorers[_index];
/// remove from exploration list
explorers[_index] = 0;
if (shipId > 0) {
delete tokenIndexToExplore[shipId];
delete tokenIndexToSector[shipId];
}
if (exploreIndexToCrew[_index] > 0) {
delete exploreIndexToCrew[_index];
}
}
/// @notice Add exploration in case contract needs to be add trxs from previous contract
/// @param _shipTokenId The Token ID that represents a ship
/// @param _sectorTokenId The Token ID that represents a sector
/// @param _crewTokenId The Token ID that represents a crew
function addExplorationByShip(
uint256 _shipTokenId, uint256 _sectorTokenId, uint256 _crewTokenId
)
external onlyCLevel whenPaused
{
uint256 index = explorers.push(_shipTokenId) - 1;
/// store exploration data
tokenIndexToExplore[_shipTokenId] = index;
tokenIndexToSector[_shipTokenId] = _sectorTokenId;
// check if there is a crew and store data and change ship stats
if (_crewTokenId > 0) {
/// store crew exploration data
exploreIndexToCrew[index] = _crewTokenId;
missions[_crewTokenId]++;
}
ethernautsStorage.setAssetCooldown(_shipTokenId, now, uint64(block.number));
}
/// @dev Creates a new Asset with the given fields. ONly available for C Levels
/// @param _creatorTokenID The asset who is father of this asset
/// @param _price asset price
/// @param _assetID asset ID
/// @param _category see Asset Struct description
/// @param _attributes see Asset Struct description
/// @param _stats see Asset Struct description
/// @param _cooldown see Asset Struct description
/// @param _cooldownEndBlock see Asset Struct description
function _buildAsset(
uint256 _creatorTokenID,
address _owner,
uint256 _price,
uint16 _assetID,
uint8 _category,
uint8 _attributes,
uint8[STATS_SIZE] _stats,
uint256 _cooldown,
uint64 _cooldownEndBlock
)
private returns (uint256)
{
uint256 tokenID = ethernautsStorage.createAsset(
_creatorTokenID,
_owner,
_price,
_assetID,
_category,
uint8(AssetState.Available),
_attributes,
_stats,
_cooldown,
_cooldownEndBlock
);
// emit the build event
Build(
_owner,
tokenID,
_assetID,
_price
);
return tokenID;
}
/// @notice Exploration Time: The time it takes to explore a Sector is dependent on the Sector Size
/// along with the Ship’s Range and Speed.
/// @param _shipRange ship range
/// @param _shipSpeed ship speed
/// @param _sectorSize sector size
function _explorationTime(
uint8 _shipRange,
uint8 _shipSpeed,
uint8 _sectorSize
) private view returns (int256) {
int256 minToExplore = 0;
minToExplore = SafeMath.min(_shipSpeed, SPEED_STAT_MAX) - 1;
minToExplore = -72 * minToExplore;
minToExplore += MAX_TIME_EXPLORE;
uint256 minRange = uint256(SafeMath.min(_shipRange, RANGE_STAT_MAX));
uint256 scaledRange = uint256(RANGE_STAT_MAX * RANGE_SCALE);
int256 minExplore = (minToExplore - MIN_TIME_EXPLORE);
minToExplore -= fraction(minExplore, int256(minRange), int256(scaledRange));
minToExplore += fraction(minToExplore, int256(_sectorSize) - int256(10), 10);
minToExplore = SafeMath.max(minToExplore, MIN_TIME_EXPLORE);
return minToExplore;
}
/// @notice calcs a perc without float or double :(
function fraction(int256 _subject, int256 _numerator, int256 _denominator)
private pure returns (int256) {
int256 division = _subject * _numerator - _subject * _denominator;
int256 total = _subject * _denominator + division;
return total / _denominator;
}
/// @notice Any C-level can fix how many seconds per blocks are currently observed.
/// @param _secs The seconds per block
function setSecondsPerBlock(uint256 _secs) external onlyCLevel {
require(_secs > 0);
secondsPerBlock = _secs;
}
}
| Exploration is complete and at most 10 Objects will return during one exploration. _shipTokenId The Token ID that represents a ship and can explore _sectorTokenId The Token ID that represents a sector and can be explored _IDs that represents a object returned from exploration _attributes that represents attributes for each object returned from exploration _stats that represents all stats for each object returned from exploration create objects returned from exploration | function explorationResults(
uint256 _shipTokenId,
uint256 _sectorTokenId,
uint16[10] _IDs,
uint8[10] _attributes,
uint8[STATS_SIZE][10] _stats
)
external onlyOracle
{
uint256 cooldown;
uint64 cooldownEndBlock;
uint256 builtBy;
(,,,,,cooldownEndBlock, cooldown, builtBy) = ethernautsStorage.assets(_shipTokenId);
address owner = ethernautsStorage.ownerOf(_shipTokenId);
require(owner != address(0));
uint256 i = 0;
for (i = 0; i < 10 && _IDs[i] > 0; i++) {
_buildAsset(
_sectorTokenId,
owner,
0,
_IDs[i],
uint8(AssetCategory.Object),
uint8(_attributes[i]),
_stats[i],
cooldown,
cooldownEndBlock
);
}
delete tokenIndexToExplore[_shipTokenId];
delete tokenIndexToSector[_shipTokenId];
}
| 1,044,230 |
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// SPDX-License-Identifier: MIT
import "@openzeppelin-3.4.0/token/ERC20/IERC20.sol";
import "@openzeppelin-3.4.0/token/ERC20/SafeERC20.sol";
import "./interfaces/Upgradeable.sol";
import "./GovToken.sol";
import "./MintCoordinator_Polygon.sol";
import "./interfaces/IMasterChef.sol";
contract MasterChef_Polygon is Upgradeable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The GOV TOKEN!
GovToken public GOV;
// Dev address.
address public devaddr;
// Block number when bonus GOV period ends.
uint256 public bonusEndBlock;
// GOV tokens created per block.
uint256 public GOVPerBlock;
// Bonus muliplier for early GOV makers.
uint256 public constant BONUS_MULTIPLIER = 0;
// unused
address public migrator;
// Info of each pool.
IMasterChef.PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => IMasterChef.UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when GOV mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
// add the GOV pool first to have ID 0
uint256 internal constant GOV_POOL_ID = 0;
event AddExternalReward(
address indexed sender,
uint256 indexed pid,
uint256 amount
);
MintCoordinator_Polygon public constant coordinator = MintCoordinator_Polygon(0x52fb1688B829BDb2BF70058f0BBfFD38af26cc2b);
mapping(IERC20 => bool) public poolExists;
modifier nonDuplicated(IERC20 _lpToken) {
require(!poolExists[_lpToken], "pool exists");
_;
}
// total deposits in a pool
mapping(uint256 => uint256) public balanceOf;
// pool rewards locked for future claim
mapping(uint256 => bool) public isLocked;
// total locked rewards for a user
mapping(address => uint256) internal _lockedRewards;
bool public notPaused;
modifier checkNoPause() {
require(notPaused || msg.sender == owner(), "paused");
_;
}
// vestingStamp for a user
mapping(address => uint256) public userStartVestingStamp;
//default value if userStartVestingStamp[user] == 0
uint256 public startVestingStamp;
uint256 public vestingDuration; // 15768000 6 months (6 * 365 * 24 * 60 * 60)
event AddAltReward(
address indexed sender,
uint256 indexed pid,
uint256 amount
);
event ClaimAltRewards(
address indexed user,
uint256 amount
);
//Mapping pid -- accumulated bnbPerGov
mapping(uint256 => uint256[]) public altRewardsRounds; // Old
//user => lastClaimedRound
mapping(address => uint256) public userAltRewardsRounds; // Old
//pid -- altRewardsPerShare
mapping(uint256 => uint256) public altRewardsPerShare;
//pid -- (user -- altRewardsPerShare)
mapping(uint256 => mapping(address => uint256)) public userAltRewardsPerShare;
bool public vestingDisabled;
uint256 internal constant IBZRX_POOL_ID = 2;
function initialize(
GovToken _GOV,
address _devaddr,
uint256 _GOVPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public onlyOwner {
require(address(GOV) == address(0), "unauthorized");
GOV = _GOV;
devaddr = _devaddr;
GOVPerBlock = _GOVPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function setVestingDuration(uint256 _vestingDuration)
external
onlyOwner
{
vestingDuration = _vestingDuration;
}
function setStartVestingStamp(uint256 _startVestingStamp)
external
onlyOwner
{
startVestingStamp = _startVestingStamp;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate)
public
onlyOwner
nonDuplicated(_lpToken)
{
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock =
block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolExists[_lpToken] = true;
poolInfo.push(
IMasterChef.PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accGOVPerShare: 0
})
);
}
// Update the given pool's GOV allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate)
public
onlyOwner
{
if (_withUpdate) {
massUpdatePools();
}
IMasterChef.PoolInfo storage pool = poolInfo[_pid];
require(address(pool.lpToken) != address(0) && poolExists[pool.lpToken], "pool not exists");
totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(
_allocPoint
);
pool.allocPoint = _allocPoint;
if (block.number < pool.lastRewardBlock) {
pool.lastRewardBlock = startBlock;
}
}
function transferTokenOwnership(address newOwner)
public
onlyOwner
{
GOV.transferOwnership(newOwner);
}
function setStartBlock(uint256 _startBlock)
public
onlyOwner
{
startBlock = _startBlock;
}
function setLocked(uint256 _pid, bool _toggle)
public
onlyOwner
{
isLocked[_pid] = _toggle;
}
function setGOVPerBlock(uint256 _GOVPerBlock)
public
onlyOwner
{
massUpdatePools();
GOVPerBlock = _GOVPerBlock;
}
function getMultiplier(uint256 _from, uint256 _to)
public
view
returns (uint256)
{
return getMultiplierPrecise(_from, _to).div(1e18);
}
function getMultiplierNow()
public
view
returns (uint256)
{
return getMultiplierPrecise(block.number - 1, block.number);
}
function getMultiplierPrecise(uint256 _from, uint256 _to)
public
view
returns (uint256)
{
return _getDecliningMultipler(_from, _to, startBlock);
}
function _getDecliningMultipler(uint256 _from, uint256 _to, uint256 _bonusStartBlock)
internal
view
returns (uint256)
{
return _to.sub(_from).mul(1e18);
/*
// _periodBlocks = 1296000 = 60 * 60 * 24 * 30 / 2 = blocks_in_30_days (assume 2 second blocks)
uint256 _bonusEndBlock = _bonusStartBlock + 1296000;
// multiplier = 10e18
// declinePerBlock = 6944444444444 = (10e18 - 1e18) / _periodBlocks
uint256 _startMultipler;
uint256 _endMultipler;
uint256 _avgMultiplier;
if (_to <= _bonusEndBlock) {
_startMultipler = SafeMath.sub(10e18,
_from.sub(_bonusStartBlock)
.mul(6944444444444)
);
_endMultipler = SafeMath.sub(10e18,
_to.sub(_bonusStartBlock)
.mul(6944444444444)
);
_avgMultiplier = (_startMultipler + _endMultipler) / 2;
return _to.sub(_from).mul(_avgMultiplier);
} else if (_from >= _bonusEndBlock) {
return _to.sub(_from).mul(1e18);
} else {
_startMultipler = SafeMath.sub(10e18,
_from.sub(_bonusStartBlock)
.mul(6944444444444)
);
_endMultipler = 1e18;
_avgMultiplier = (_startMultipler + _endMultipler) / 2;
return _bonusEndBlock.sub(_from).mul(_avgMultiplier).add(
_to.sub(_bonusEndBlock).mul(1e18)
);
}*/
}
function _pendingGOV(uint256 _pid, address _user)
internal
view
returns (uint256)
{
IMasterChef.PoolInfo storage pool = poolInfo[_pid];
IMasterChef.UserInfo storage user = userInfo[_pid][_user];
uint256 accGOVPerShare = pool.accGOVPerShare.mul(1e18);
uint256 lpSupply = balanceOf[_pid];
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier =
getMultiplierPrecise(pool.lastRewardBlock, block.number);
uint256 GOVReward =
multiplier.mul(GOVPerBlock).mul(pool.allocPoint).div(
totalAllocPoint
);
accGOVPerShare = accGOVPerShare.add(
GOVReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accGOVPerShare).div(1e30).sub(user.rewardDebt);
}
function pendingAltRewards(uint256 pid, address _user)
external
view
returns (uint256)
{
return _pendingAltRewards(pid, _user);
}
//Splitted by pid in case if we want to distribute altRewards to other pids like bzrx
function _pendingAltRewards(uint256 pid, address _user)
internal
view
returns (uint256)
{
uint256 userSupply = userInfo[pid][_user].amount;
uint256 _altRewardsPerShare = altRewardsPerShare[pid];
if (_altRewardsPerShare == 0)
return 0;
if (userSupply == 0)
return 0;
uint256 _userAltRewardsPerShare = userAltRewardsPerShare[pid][_user];
//Handle the backcapability,
//when all user claim altrewards at least once we can remove this check
if(_userAltRewardsPerShare == 0 && pid == GOV_POOL_ID){
//Or didnt claim or didnt migrate
//check if migrate
uint256 _lastClaimedRound = userAltRewardsRounds[_user];
//Never claimed yet
if (_lastClaimedRound != 0) {
_lastClaimedRound -= 1; //correct index to start from 0
_userAltRewardsPerShare = altRewardsRounds[pid][_lastClaimedRound];
}
}
return (_altRewardsPerShare.sub(_userAltRewardsPerShare)).mul(userSupply).div(1e12);
}
// View function to see pending GOVs on frontend.
function pendingGOV(uint256 _pid, address _user)
external
view
returns (uint256)
{
return _pendingGOV(_pid, _user);
}
function unlockedRewards(address _user)
public
view
returns (uint256)
{
uint256 _locked = _lockedRewards[_user];
if(_locked == 0) {
return 0;
}
return calculateUnlockedRewards(_locked, now, userStartVestingStamp[_user]);
}
function calculateUnlockedRewards(uint256 _locked, uint256 currentStamp, uint256 _userStartVestingStamp)
public
view
returns (uint256)
{
//Unlock everything
if(vestingDisabled){
return _locked;
}
//Vesting is not started
if(startVestingStamp == 0 || vestingDuration == 0){
return 0;
}
if(_userStartVestingStamp == 0) {
_userStartVestingStamp = startVestingStamp;
}
uint256 _cliffDuration = currentStamp.sub(_userStartVestingStamp);
if(_cliffDuration >= vestingDuration)
return _locked;
return _cliffDuration.mul(_locked.div(vestingDuration)); // _locked.div(vestingDuration) is unlockedPerSecond
}
function lockedRewards(address _user)
public
view
returns (uint256)
{
return _lockedRewards[_user].sub(unlockedRewards(_user));
}
function toggleVesting(bool _isEnabled) external onlyOwner {
vestingDisabled = !_isEnabled;
}
function togglePause(bool _isPaused) external onlyOwner {
notPaused = !_isPaused;
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public checkNoPause {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function massMigrateToBalanceOf() public onlyOwner {
require(!notPaused, "!paused");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
balanceOf[pid] = poolInfo[pid].lpToken.balanceOf(address(this));
}
massUpdatePools();
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public checkNoPause {
IMasterChef.PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = balanceOf[_pid];
uint256 _GOVPerBlock = GOVPerBlock;
uint256 _allocPoint = pool.allocPoint;
if (lpSupply == 0 || _GOVPerBlock == 0 || _allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplierPrecise(pool.lastRewardBlock, block.number);
uint256 GOVReward =
multiplier.mul(_GOVPerBlock).mul(_allocPoint).div(
totalAllocPoint
);
// 250m = 250 * 1e6
if (coordinator.totalMinted() >= 250*1e6*1e18) {
pool.allocPoint = 0;
return;
}
coordinator.mint(devaddr, GOVReward.div(1e19));
coordinator.mint(address(this), GOVReward.div(1e18));
pool.accGOVPerShare = pool.accGOVPerShare.add(
GOVReward.div(1e6).div(lpSupply)
);
pool.lastRewardBlock = block.number;
}
// Anyone can contribute GOV to a given pool
function addExternalReward(uint256 _amount) public checkNoPause {
IMasterChef.PoolInfo storage pool = poolInfo[GOV_POOL_ID];
require(block.number > pool.lastRewardBlock, "rewards not started");
uint256 lpSupply = balanceOf[GOV_POOL_ID];
require(lpSupply != 0, "no deposits");
updatePool(GOV_POOL_ID);
GOV.transferFrom(
address(msg.sender),
address(this),
_amount
);
pool.accGOVPerShare = pool.accGOVPerShare.add(
_amount.mul(1e12).div(lpSupply)
);
emit AddExternalReward(msg.sender, GOV_POOL_ID, _amount);
}
// Anyone can contribute native token rewards to GOV pool stakers
function addAltReward() public payable checkNoPause {
IMasterChef.PoolInfo storage pool = poolInfo[IBZRX_POOL_ID];
require(block.number > pool.lastRewardBlock, "rewards not started");
uint256 lpSupply = balanceOf[IBZRX_POOL_ID];
require(lpSupply != 0, "no deposits");
updatePool(IBZRX_POOL_ID);
altRewardsPerShare[IBZRX_POOL_ID] = altRewardsPerShare[IBZRX_POOL_ID]
.add(msg.value.mul(1e12).div(lpSupply));
emit AddAltReward(msg.sender, IBZRX_POOL_ID, msg.value);
}
// Deposit LP tokens to MasterChef for GOV allocation.
function deposit(uint256 _pid, uint256 _amount) public checkNoPause {
poolInfo[_pid].lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
_deposit(_pid, _amount);
}
function _deposit(uint256 _pid, uint256 _amount) internal {
IMasterChef.PoolInfo storage pool = poolInfo[_pid];
IMasterChef.UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 userAmount = user.amount;
uint256 pending;
uint256 pendingAlt;
if (userAmount != 0) {
pending = userAmount
.mul(pool.accGOVPerShare)
.div(1e12)
.sub(user.rewardDebt);
}
if (_pid == GOV_POOL_ID || _pid == IBZRX_POOL_ID) {
pendingAlt = _pendingAltRewards(_pid, msg.sender);
//Update userAltRewardsPerShare even if user got nothing in the current round
userAltRewardsPerShare[_pid][msg.sender] = altRewardsPerShare[_pid];
}
if (_amount != 0) {
balanceOf[_pid] = balanceOf[_pid].add(_amount);
userAmount = userAmount.add(_amount);
emit Deposit(msg.sender, _pid, _amount);
}
user.rewardDebt = userAmount.mul(pool.accGOVPerShare).div(1e12);
user.amount = userAmount;
//user vestingStartStamp recalculation is done in safeGOVTransfer
safeGOVTransfer(_pid, pending);
if (pendingAlt != 0) {
sendValueIfPossible(msg.sender, pendingAlt);
}
}
function claimReward(uint256 _pid) public checkNoPause {
_deposit(_pid, 0);
}
function compoundReward(uint256 _pid) public checkNoPause {
uint256 balance = GOV.balanceOf(msg.sender);
_deposit(_pid, 0);
// locked pools are ignored since they auto-compound
if (!isLocked[_pid]) {
balance = GOV.balanceOf(msg.sender).sub(balance);
if (balance != 0)
deposit(GOV_POOL_ID, balance);
}
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public checkNoPause {
IMasterChef.PoolInfo storage pool = poolInfo[_pid];
IMasterChef.UserInfo storage user = userInfo[_pid][msg.sender];
uint256 userAmount = user.amount;
require(_amount != 0 && userAmount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = userAmount
.mul(pool.accGOVPerShare)
.div(1e12)
.sub(user.rewardDebt);
uint256 pendingAlt;
IERC20 lpToken = pool.lpToken;
if (_pid == GOV_POOL_ID || _pid == IBZRX_POOL_ID) {
uint256 availableAmount = userAmount.sub(lockedRewards(msg.sender));
if (_amount > availableAmount) {
_amount = availableAmount;
}
pendingAlt = _pendingAltRewards(_pid, msg.sender);
//Update userAltRewardsPerShare even if user got nothing in the current round
userAltRewardsPerShare[_pid][msg.sender] = altRewardsPerShare[_pid];
}
balanceOf[_pid] = balanceOf[_pid].sub(_amount);
userAmount = userAmount.sub(_amount);
user.rewardDebt = userAmount.mul(pool.accGOVPerShare).div(1e12);
user.amount = userAmount;
lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
//user vestingStartStamp recalculation is done in safeGOVTransfer
safeGOVTransfer(_pid, pending);
if (pendingAlt != 0) {
sendValueIfPossible(msg.sender, pendingAlt);
}
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public checkNoPause {
IMasterChef.PoolInfo storage pool = poolInfo[_pid];
IMasterChef.UserInfo storage user = userInfo[_pid][msg.sender];
uint256 _amount = user.amount;
uint256 pendingAlt;
IERC20 lpToken = pool.lpToken;
if (_pid == GOV_POOL_ID || _pid == IBZRX_POOL_ID) {
uint256 availableAmount = _amount.sub(lockedRewards(msg.sender));
if (_amount > availableAmount) {
_amount = availableAmount;
}
pendingAlt = _pendingAltRewards(_pid, msg.sender);
//Update userAltRewardsPerShare even if user got nothing in the current round
userAltRewardsPerShare[_pid][msg.sender] = altRewardsPerShare[_pid];
}
lpToken.safeTransfer(address(msg.sender), _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
balanceOf[_pid] = balanceOf[_pid].sub(_amount);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accGOVPerShare).div(1e12);
if (pendingAlt != 0) {
sendValueIfPossible(msg.sender, pendingAlt);
}
}
function safeGOVTransfer(uint256 _pid, uint256 _amount) internal {
if (_amount == 0) {
return;
}
uint256 GOVBal = GOV.balanceOf(address(this));
if (_amount > GOVBal) {
_amount = GOVBal;
}
if (isLocked[_pid]) {
uint256 _locked = _lockedRewards[msg.sender];
_lockedRewards[msg.sender] = _locked.add(_amount);
userStartVestingStamp[msg.sender] = calculateVestingStartStamp(now, userStartVestingStamp[msg.sender], _locked, _amount);
_deposit(GOV_POOL_ID, _amount);
} else {
GOV.transfer(msg.sender, _amount);
}
}
//This function will be internal after testing,
function calculateVestingStartStamp(uint256 currentStamp, uint256 _userStartVestingStamp, uint256 _lockedAmount, uint256 _depositAmount)
public
view
returns(uint256)
{
//VestingStartStamp will be distributed between
//_userStartVestingStamp (min) and currentStamp (max) depends on _lockedAmount and _depositAmount
//To avoid calculation on limit values
if(_lockedAmount == 0) return startVestingStamp;
if(_depositAmount >= _lockedAmount) return currentStamp;
if(_depositAmount == 0) return _userStartVestingStamp;
//Vesting is not started, set 0 as default value
if(startVestingStamp == 0 || vestingDuration == 0){
return 0;
}
if(_userStartVestingStamp == 0) {
_userStartVestingStamp = startVestingStamp;
}
uint256 cliffDuration = currentStamp.sub(_userStartVestingStamp);
uint256 depositShare = _depositAmount.mul(1e12).div(_lockedAmount);
return _userStartVestingStamp.add(cliffDuration.mul(depositShare).div(1e12));
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
// Custom logic - helpers
function getPoolInfos() external view returns(IMasterChef.PoolInfo[] memory poolInfos) {
uint256 length = poolInfo.length;
poolInfos = new IMasterChef.PoolInfo[](length);
for (uint256 pid = 0; pid < length; ++pid) {
poolInfos[pid] = poolInfo[pid];
}
}
function getOptimisedUserInfos(address _user) external view returns(uint256[4][] memory userInfos) {
uint256 length = poolInfo.length;
userInfos = new uint256[4][](length);
for (uint256 pid = 0; pid < length; ++pid) {
userInfos[pid][0] = userInfo[pid][_user].amount;
userInfos[pid][1] = _pendingGOV(pid, _user);
userInfos[pid][2] = isLocked[pid] ? 1 : 0;
userInfos[pid][3] = (pid == GOV_POOL_ID || pid == IBZRX_POOL_ID) ? _pendingAltRewards(pid, _user) : 0;
}
}
function getUserInfos(address _wallet) external view returns(IMasterChef.UserInfo[] memory userInfos) {
uint256 length = poolInfo.length;
userInfos = new IMasterChef.UserInfo[](length);
for (uint256 pid = 0; pid < length; ++pid) {
userInfos[pid] = userInfo[pid][_wallet];
}
}
function getPendingGOV(address _user) external view returns(uint256[] memory pending) {
uint256 length = poolInfo.length;
pending = new uint256[](length);
for (uint256 pid = 0; pid < length; ++pid) {
pending[pid] = _pendingGOV(pid, _user);
}
}
function sendValueIfPossible(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{ value: amount }("");
if (!success) {
(success, ) = devaddr.call{ value: amount }("");
if (success)
emit ClaimAltRewards(devaddr, amount);
} else {
emit ClaimAltRewards(recipient, amount);
}
}
//Should be called only once after migration to new calculation
function setInitialAltRewardsPerShare()
external
onlyOwner
{
uint256 index = altRewardsRounds[GOV_POOL_ID].length;
if(index == 0) {
return;
}
uint256 _currentRound = altRewardsRounds[GOV_POOL_ID].length;
uint256 currentAccumulatedAltRewards = altRewardsRounds[GOV_POOL_ID][_currentRound-1];
altRewardsPerShare[GOV_POOL_ID] = currentAccumulatedAltRewards;
}
} | Anyone can contribute native token rewards to GOV pool stakers | function addAltReward() public payable checkNoPause {
IMasterChef.PoolInfo storage pool = poolInfo[IBZRX_POOL_ID];
require(block.number > pool.lastRewardBlock, "rewards not started");
uint256 lpSupply = balanceOf[IBZRX_POOL_ID];
require(lpSupply != 0, "no deposits");
updatePool(IBZRX_POOL_ID);
altRewardsPerShare[IBZRX_POOL_ID] = altRewardsPerShare[IBZRX_POOL_ID]
.add(msg.value.mul(1e12).div(lpSupply));
emit AddAltReward(msg.sender, IBZRX_POOL_ID, msg.value);
}
| 15,815,779 |
// SPDX-License-Identifier: No License (None)
pragma solidity ^0.8.0;
import "./TransferHelper.sol";
interface IERC20 {
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function transfer(address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
}
interface IValidator {
// returns rate (with 18 decimals) = Token B price / Token A price
function getRate(address tokenA, address tokenB) external returns (uint256);
// returns: user balance, native (foreign for us) encoded balance, foreign (native for us) encoded balance
function checkBalances(address factory, address[] calldata user) external returns(uint256);
// returns: user balance
function checkBalance(address factory, address user) external returns(uint256);
// returns: oracle fee
function getOracleFee(uint256 req) external returns(uint256); //req: 1 - cancel, 2 - claim, returns: value
}
interface ISmart {
function requestCompensation(address user, uint256 feeAmount) external returns(bool);
}
interface IAuction {
function contributeFromSmartSwap(address payable user) external payable returns (bool);
function contributeFromSmartSwap(address token, uint256 amount, address user) external returns (bool);
}
abstract contract Ownable {
address internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
/* we use proxy, so owner will be set in initialize() function
constructor () {
_owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
*/
/**
* @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() == msg.sender, "Ownable: caller is not the owner");
_;
}
/**
* @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;
}
}
contract SmartSwap is Ownable {
struct Cancel {
uint64 pairID; // pair ID
address sender; // user who has to receive canceled amount
uint256 amount; // amount of token user want to cancel from order
//uint128 foreignBalance; // amount of token already swapped (on other chain)
}
struct Claim {
uint64 pairID; // pair ID
address sender; // address who send tokens to swap
address receiver; // address who has to receive swapped amount
uint64 claimID; // uniq claim ID
bool isInvestment; // is claim to contributeFromSmartSwap
uint128 amount; // amount of foreign tokens user want to swap
uint128 currentRate;
uint256 foreignBalance; //[0] foreignBalance, [1] foreignSpent, [2] nativeSpent, [3] nativeRate
}
struct Pair {
address tokenA;
address tokenB;
}
address constant NATIVE_COINS = 0x0000000000000000000000000000000000000009; // 1 - BNB, 2 - ETH, 3 - BTC
uint256 constant NOMINATOR = 10**18;
uint256 constant MAX_AMOUNT = 2**128;
address public foreignFactory;
address payable public validator;
uint256 public rateDiffLimit; // allowed difference (in percent) between LP provided rate and Oracle rate.
mapping(address => bool) public isSystem; // system address mey change fee amount
address public auction; // auction address
address public contractSmart; // the contract address to request Smart token in exchange of fee
mapping (address => uint256) licenseeFee; // the licensee may set personal fee (in percent wih 2 decimals). It have to compensate this fee with own tokens.
mapping (address => address) licenseeCompensator; // licensee contract which will compensate fee with tokens
mapping(address => bool) public isExchange; // is Exchange address
mapping(address => bool) public isExcludedSender; // address excluded from receiving SMART token as fee compensation
// fees
uint256 public swapGasReimbursement; // percentage of swap Gas Reimbursement by SMART tokens
uint256 public companyFeeReimbursement; // percentage of company Fee Reimbursement by SMART tokens
uint256 public cancelGasReimbursement; // percentage of cancel Gas Reimbursement by SMART tokens
uint256 public companyFee; // the fee (in percent wih 2 decimals) that received by company. 30 - means 0.3%
uint256 public processingFee; // the fee in base coin, to compensate Gas when back-end call claimTokenBehalf()
address public feeReceiver; // address which receive the fee (by default is validator)
uint256 private collectedFees; // amount of collected fee (starts from 1 to avoid additional gas usage)
mapping(address => uint256) public decimals; // token address => token decimals
uint256 public pairIDCounter;
mapping(uint256 => Pair) public getPairByID;
mapping(address => mapping(address => uint256)) public getPairID; // tokenA => tokenB => pair ID or 0 if not exist
mapping(uint256 => uint256) public totalSupply; // pairID => totalSupply amount of tokenA on the pair
// hashAddress = address(keccak256(tokenA, tokenB, sender, receiver))
mapping(address => uint256) private _balanceOf; // hashAddress => amount of tokenA
mapping(address => Cancel) public cancelRequest; // hashAddress => amount of tokenA to cancel
mapping(address => Claim) public claimRequest; // hashAddress => amount of tokenA to swap
mapping(address => bool) public isLiquidityProvider; // list of Liquidity Providers
uint256 claimIdCounter; // counter of claim requests
// ============================ Events ============================
event PairAdded(address indexed tokenA, address indexed tokenB, uint256 indexed pairID);
event PairRemoved(address indexed tokenA, address indexed tokenB, uint256 indexed pairID);
event SwapRequest(
address indexed tokenA,
address indexed tokenB,
address indexed sender,
address receiver,
uint256 amountA,
bool isInvestment,
uint128 minimumAmountToClaim, // do not claim on user behalf less of this amount. Only exception if order fulfilled.
uint128 limitPice // Do not match user if token A price less this limit
);
event CancelRequest(address indexed hashAddress, uint256 amount);
event CancelApprove(address indexed hashAddress, uint256 newBalance);
event ClaimRequest(address indexed hashAddress, uint64 claimID, uint256 amount, bool isInvestment);
event ClaimApprove(address indexed hashAddress, uint64 claimID, uint256 nativeAmount, uint256 foreignAmount, bool isInvestment);
event ExchangeInvestETH(address indexed exchange, address indexed whom, uint256 value);
event SetSystem(address indexed system, bool active);
event SetLicensee(address indexed system, address indexed compensator);
/**
* @dev Throws if called by any account other than the system.
*/
modifier onlySystem() {
require(isSystem[msg.sender] || owner() == msg.sender, "Caller is not the system");
_;
}
// run only once from proxy
function initialize(address newOwner) external {
require(newOwner != address(0) && _owner == address(0)); // run only once
_owner = newOwner;
emit OwnershipTransferred(address(0), msg.sender);
rateDiffLimit = 5; // allowed difference (in percent) between LP provided rate and Oracle rate.
swapGasReimbursement = 100; // percentage of swap Gas Reimbursement by SMART tokens
companyFeeReimbursement = 100; // percentage of company Fee Reimbursement by SMART tokens
cancelGasReimbursement = 100; // percentage of cancel Gas Reimbursement by SMART tokens
companyFee = 0; // the fee (in percent wih 2 decimals) that received by company. 30 - means 0.3%
collectedFees = 1; // amount of collected fee (starts from 1 to avoid additional gas usage)
}
// get amount of collected fees that can be claimed
function getColletedFees() external view returns (uint256) {
// collectedFees starts from 1 to avoid additional gas usage to initiate storage (when collectedFees = 0)
return collectedFees - 1;
}
// claim fees by feeReceiver
function claimFee() external returns (uint256 feeAmount)
{
require(msg.sender == feeReceiver);
feeAmount = collectedFees - 1;
collectedFees = 1;
TransferHelper.safeTransferETH(msg.sender, feeAmount);
}
function balanceOf(address hashAddress) external view returns(uint256) {
return _balanceOf[hashAddress];
}
// return balance for swap
function getBalance(
address tokenA,
address tokenB,
address sender,
address receiver
)
external
view
returns (uint256)
{
return _balanceOf[_getHashAddress(tokenA, tokenB, sender, receiver)];
}
function getHashAddress(
address tokenA,
address tokenB,
address sender,
address receiver
)
external
pure
returns (address)
{
return _getHashAddress(tokenA, tokenB, sender, receiver);
}
//user should approve tokens transfer before calling this function.
//if no licensee set it to address(0)
function swap(
address tokenA,
address tokenB,
address receiver,
uint256 amountA,
address licensee,
bool isInvestment,
uint128 minimumAmountToClaim, // do not claim on user behalf less of this amount. Only exception if order fulfilled.
uint128 limitPice // Do not match user if token A price less this limit
)
external
payable
returns (bool)
{
_transferFee(tokenA, amountA, msg.sender, licensee);
_swap(tokenA, tokenB, msg.sender, receiver, amountA, isInvestment, minimumAmountToClaim, limitPice);
return true;
}
function cancel(
address tokenA,
address tokenB,
address receiver,
uint256 amountA //amount of tokenA to cancel
)
external
payable
returns (bool)
{
_cancel(tokenA, tokenB, msg.sender, receiver, amountA);
return true;
}
function claimTokenBehalf(
address tokenA, // foreignToken
address tokenB, // nativeToken
address sender,
address receiver,
bool isInvestment,
uint128 amountA, //amount of tokenA that has to be swapped
uint128 currentRate, // rate with 18 decimals: tokenA price / tokenB price
uint256 foreignBalance // total tokens amount sent by user to pair on other chain
)
external
onlySystem
returns (bool)
{
_claimTokenBehalf(tokenA, tokenB, sender, receiver, isInvestment, amountA, currentRate, foreignBalance);
return true;
}
// add liquidity to counterparty
function addLiquidityAndClaimBehalf(
address tokenA, // Native token
address tokenB, // Foreign token
address receiver,
bool isInvestment,
uint128 amountA, //amount of tokenA that has to be swapped
uint128 currentRate, // rate with 18 decimals: tokenB price / tokenA price
uint256 foreignBalance, // total tokens amount sent by user to pair on other chain
address senderCounterparty,
address receiverCounterparty
)
external
payable
onlySystem
returns (bool)
{
_transferFee(tokenA, amountA, msg.sender, address(0));
_swap(tokenA, tokenB, msg.sender, receiver, amountA, false,0,0);
uint256 amountB = amountA * 10**(18+decimals[tokenB]-decimals[tokenA]) / currentRate;
_claimTokenBehalf(tokenB, tokenA, senderCounterparty, receiverCounterparty, isInvestment, uint128(amountB), currentRate, foreignBalance);
return true;
}
function balanceCallback(address hashAddress, uint256 foreignBalance) external returns(bool) {
require (validator == msg.sender, "Not validator");
_cancelApprove(hashAddress, foreignBalance);
return true;
}
function balancesCallback(
address hashAddress,
uint256 foreignBalance, // total user's tokens balance on foreign chain
uint256 foreignSpent, // total tokens spent by SmartSwap pair
uint256 nativeEncoded // (nativeRate, nativeSpent) = _decode(nativeEncoded)
)
external
returns(bool)
{
require (validator == msg.sender, "Not validator");
_claimBehalfApprove(hashAddress, foreignBalance, foreignSpent, nativeEncoded);
return true;
}
// get system variables for debugging
function getPairVars(uint256 pairID) external view returns (uint256 native, uint256 foreign, uint256 foreignRate) {
address nativeHash = _getHashAddress(getPairByID[pairID].tokenA, getPairByID[pairID].tokenB, address(0), address(0));
address foreignHash = _getHashAddress(getPairByID[pairID].tokenB, getPairByID[pairID].tokenA, address(0), address(0));
// native - amount of native tokens that swapped from available foreign
native = _balanceOf[nativeHash];
// foreign = total foreign tokens already swapped
// foreignRate = rate (native price / foreign price) of available foreign tokens on other chain
(foreignRate, foreign) = _decode(_balanceOf[foreignHash]);
// Example: assume system vars = 0, rate of prices ETH/BNB = 2 (or BNB/ETH = 0.5)
// on ETH chain:
// 1. claim ETH for 60 BNB == 60 * 0.5 = 30 ETH,
// set: foreign = 60 BNB, foreignRate = 0.5 BNB/ETH prices (already swapped BNB)
//
// on BSC chain:
// 2. claim BNB for 20 ETH, assume new rate of prices ETH/BNB = 4 (or BNB/ETH = 0.25)
// get from ETH chain foreign(ETH) = 60 BNB, foreignRate(ETH) = 0.5 BNB/ETH prices
// available amount of already swapped BNB = 60 BNB (foreign from ETH) - 0 BNB (native) = 60 BNB with rate 0.5 BNB/ETH
// claimed BNB amount = 20 ETH / 0.5 BNB/ETH = 40 BNB (we use rate of already swapped BNB)
// set: native = 40 BNB (we use BNB that was already swapped on step 1)
//
// 3. New claim BNB for 30 ETH, assume new rate of prices ETH/BNB = 4 (or BNB/ETH = 0.25)
// get from ETH chain foreign(ETH) = 60 BNB, foreignRate(ETH) = 0.5 BNB/ETH prices
// available amount of already swapped BNB = 60 BNB (foreign from ETH) - 40 BNB (native) = 20 BNB with rate 0.5 BNB/ETH
// 20 BNB * 0.5 = 10 ETH (we claimed 20 BNB for 10 ETH with already swapped rate)
// set: native = 40 BNB + 20 BNB = 60 BNB (we use all BNB that was already swapped on step 1)
// claimed rest BNB amount for (30-10) ETH = 20 ETH / 0.25 BNB/ETH = 80 BNB (we use new rate)
// set: foreign = 20 ETH, foreignRate = 0.25 BNB/ETH prices (already swapped ETH)
}
// ================== For Jointer Auction =========================================================================
// ETH side
// function for invest ETH from from exchange on user behalf
function contributeWithEtherBehalf(address payable _whom) external payable returns (bool) {
require(isExchange[msg.sender], "Not an Exchange address");
address tokenA = address(2); // ETH (native coin)
address tokenB = address(1); // BNB (foreign coin)
uint256 amount = msg.value - processingFee;
emit ExchangeInvestETH(msg.sender, _whom, msg.value);
_transferFee(tokenA, amount, _whom, address(0)); // no licensee
_swap(tokenA, tokenB, _whom, auction, amount, true,0,0);
return true;
}
// BSC side
// tokenB - foreign token address or address(1) for ETH
// amountB - amount of foreign tokens or ETH
function claimInvestmentBehalf(
address tokenB, // foreignToken
address user,
uint128 amountB, //amount of tokenB that has to be swapped
uint128 currentRate, // rate with 18 decimals: tokenB price / Native coin price
uint256 foreignBalance // total tokens amount sent by user to pair on other chain
)
external
onlySystem
returns (bool)
{
address tokenA = address(1); // BNB (native coin)
_claimTokenBehalf(tokenB, tokenA, user, auction, true, amountB, currentRate, foreignBalance);
return true;
}
// ================= END For Jointer Auction ===========================================================================
// ============================ Restricted functions ============================
// set processing fee - amount that have to be paid on other chain to claimTokenBehalf.
// Set in amount of native coins (BNB or ETH)
function setProcessingFee(uint256 _fee) external onlySystem returns(bool) {
processingFee = _fee;
return true;
}
// set licensee compensator contract address, if this address is address(0) - remove licensee.
// compensator contract has to compensate the fee by other tokens.
// licensee fee in percent with 2 decimals. I.e. 10 = 0.1%
function setLicensee(address _licensee, address _compensator, uint256 _fee) external onlySystem returns(bool) {
licenseeCompensator[_licensee] = _compensator;
require(_fee < 10000, "too big fee"); // fee should be less then 100%
licenseeFee[_licensee] = _fee;
emit SetLicensee(_licensee, _compensator);
return true;
}
// set licensee fee in percent with 2 decimals. I.e. 10 = 0.1%
function setLicenseeFee(uint256 _fee) external returns(bool) {
require(licenseeCompensator[msg.sender] != address(0), "licensee is not registered");
require(_fee < 10000, "too big fee"); // fee should be less then 100%
licenseeFee[msg.sender] = _fee;
return true;
}
// ============================ Owner's functions ============================
//the fee (in percent wih 2 decimals) that received by company. 30 - means 0.3%
function setCompanyFee(uint256 _fee) external onlyOwner returns(bool) {
require(_fee < 10000, "too big fee"); // fee should be less then 100%
companyFee = _fee;
return true;
}
// Reimbursement Percentage without decimals: 100 = 100%
function setReimbursementPercentage (uint256 id, uint256 _fee) external onlyOwner returns(bool) {
if (id == 1) swapGasReimbursement = _fee; // percentage of swap Gas Reimbursement by SMART tokens
else if (id == 2) cancelGasReimbursement = _fee; // percentage of cancel Gas Reimbursement by SMART tokens
else if (id == 3) companyFeeReimbursement = _fee; // percentage of company Fee Reimbursement by SMART tokens
return true;
}
function setSystem(address _system, bool _active) external onlyOwner returns(bool) {
isSystem[_system] = _active;
emit SetSystem(_system, _active);
return true;
}
function setValidator(address payable _validator) external onlyOwner returns(bool) {
validator = _validator;
return true;
}
function setForeignFactory(address _addr) external onlyOwner returns(bool) {
foreignFactory = _addr;
return true;
}
function setFeeReceiver(address _addr) external onlyOwner returns(bool) {
feeReceiver = _addr;
return true;
}
function setMSSContract(address _addr) external onlyOwner returns(bool) {
contractSmart = _addr;
return true;
}
function setAuction(address _addr) external onlyOwner returns(bool) {
auction = _addr;
return true;
}
// for ETH side only
function changeExchangeAddress(address _which,bool _bool) external onlyOwner returns(bool){
isExchange[_which] = _bool;
return true;
}
function changeExcludedAddress(address _which,bool _bool) external onlyOwner returns(bool){
isExcludedSender[_which] = _bool;
return true;
}
function createPair(address tokenA, uint256 decimalsA, address tokenB, uint256 decimalsB) public onlyOwner returns (uint256) {
require(getPairID[tokenA][tokenB] == 0, "Pair exist");
uint256 pairID = ++pairIDCounter;
getPairID[tokenA][tokenB] = pairID;
getPairByID[pairID] = Pair(tokenA, tokenB);
if (decimals[tokenA] == 0) decimals[tokenA] = decimalsA;
if (decimals[tokenB] == 0) decimals[tokenB] = decimalsB;
return pairID;
}
// ============================ Internal functions ============================
function _swap(
address tokenA, // nativeToken
address tokenB, // foreignToken
address sender,
address receiver,
uint256 amountA,
bool isInvestment,
uint128 minimumAmountToClaim, // do not claim on user behalf less of this amount. Only exception if order fulfilled.
uint128 limitPice // Do not match user if token A price less this limit
)
internal
{
uint256 pairID = getPairID[tokenA][tokenB];
require(pairID != 0, "Pair not exist");
if (tokenA > NATIVE_COINS) {
TransferHelper.safeTransferFrom(tokenA, sender, address(this), amountA);
}
// (amount >= msg.value) is checking when pay fee in the function transferFee()
address hashAddress = _getHashAddress(tokenA, tokenB, sender, receiver);
_balanceOf[hashAddress] += amountA;
totalSupply[pairID] += amountA;
emit SwapRequest(tokenA, tokenB, sender, receiver, amountA, isInvestment, minimumAmountToClaim, limitPice);
}
function _cancel(
address tokenA, // nativeToken
address tokenB, // foreignToken
address sender,
address receiver,
uint256 amountA //amount of tokenA to cancel
//uint128 foreignBalance // amount of tokenA swapped by hashAddress (get by server-side)
)
internal
{
require(msg.value >= IValidator(validator).getOracleFee(1), "Insufficient fee"); // check oracle fee for Cancel request
address hashAddress = _getHashAddress(tokenA, tokenB, sender, receiver);
uint256 pairID = getPairID[tokenA][tokenB];
require(pairID != 0, "Pair not exist");
if (cancelRequest[hashAddress].amount == 0) { // new cancel request
uint256 balance = _balanceOf[hashAddress];
require(balance >= amountA && amountA != 0, "Wrong amount");
totalSupply[pairID] = totalSupply[pairID] - amountA;
_balanceOf[hashAddress] = balance - amountA;
} else { // repeat cancel request in case oracle issues.
amountA = cancelRequest[hashAddress].amount;
}
cancelRequest[hashAddress] = Cancel(uint64(pairID), sender, amountA);
// transfer fee to validator. May be changed to request tokens for compensation
TransferHelper.safeTransferETH(feeReceiver, msg.value);
if(contractSmart != address(0) && !isExcludedSender[sender]) {
uint256 feeAmount = msg.value * cancelGasReimbursement / 100;
if (feeAmount != 0)
ISmart(contractSmart).requestCompensation(sender, feeAmount);
}
// request Oracle for fulfilled amount from hashAddress
IValidator(validator).checkBalance(foreignFactory, hashAddress);
emit CancelRequest(hashAddress, amountA);
//emit CancelRequest(tokenA, tokenB, sender, receiver, amountA);
}
function _cancelApprove(address hashAddress, uint256 foreignBalance) internal {
Cancel memory c = cancelRequest[hashAddress];
delete cancelRequest[hashAddress];
//require(c.foreignBalance == foreignBalance, "Oracle error");
uint256 balance = _balanceOf[hashAddress];
uint256 amount = uint256(c.amount);
uint256 pairID = uint256(c.pairID);
if (foreignBalance <= balance) {
//approved - transfer token to its sender
_transfer(getPairByID[pairID].tokenA, c.sender, amount);
} else {
//disapproved
balance += amount;
_balanceOf[hashAddress] = balance;
totalSupply[pairID] += amount;
}
emit CancelApprove(hashAddress, balance);
}
function _claimTokenBehalf(
address tokenA, // foreignToken
address tokenB, // nativeToken
address sender,
address receiver,
bool isInvestment,
uint128 amountA, //amount of tokenA that has to be swapped
uint128 currentRate, // rate with 18 decimals: tokenA price / tokenB price
uint256 foreignBalance // total tokens amount sent bu user to pair on other chain
// [1] foreignSpent, [2] nativeSpent, [3] nativeRate
)
internal
{
uint256 pairID = getPairID[tokenB][tokenA]; // getPairID[nativeToken][foreignToken]
require(pairID != 0, "Pair not exist");
// check rate
uint256 diffRate = uint256(currentRate) * 100 / IValidator(validator).getRate(tokenB, tokenA);
uint256 diffLimit = rateDiffLimit;
require(diffRate >= 100 - diffLimit && diffRate <= 100 + diffLimit, "Wrong rate");
uint64 claimID;
address hashAddress = _getHashAddress(tokenA, tokenB, sender, receiver);
if (claimRequest[hashAddress].amount == 0) { // new claim request
_balanceOf[hashAddress] += uint256(amountA); // total swapped amount of foreign token
claimID = uint64(++claimIdCounter);
} else { // repeat claim request in case oracle issues.
claimID = claimRequest[hashAddress].claimID;
if (amountA == 0) { // cancel claim request
emit ClaimApprove(hashAddress, claimID, 0, 0, claimRequest[hashAddress].isInvestment);
_balanceOf[hashAddress] = _balanceOf[hashAddress] - claimRequest[hashAddress].amount;
delete claimRequest[hashAddress];
return;
}
amountA = claimRequest[hashAddress].amount;
}
address[] memory users = new address[](3);
users[0] = hashAddress;
users[1] = _getHashAddress(tokenA, tokenB, address(0), address(0)); // Native hash address on foreign chain
users[2] = _getHashAddress(tokenB, tokenA, address(0), address(0)); // Foreign hash address on foreign chain
claimRequest[hashAddress] = Claim(uint64(pairID), sender, receiver, claimID, isInvestment, amountA, currentRate, foreignBalance);
IValidator(validator).checkBalances(foreignFactory, users);
emit ClaimRequest(hashAddress, claimID, amountA, isInvestment);
//emit ClaimRequest(tokenA, tokenB, sender, receiver, amountA);
}
// Approve or disapprove claim request.
function _claimBehalfApprove(
address hashAddress,
uint256 foreignBalance, // total user's tokens balance on foreign chain
uint256 foreignSpent, // total tokens spent by SmartSwap pair
uint256 nativeEncoded // (nativeSpent, nativeRate) = _decode(nativeEncoded)
)
internal
{
Claim memory c = claimRequest[hashAddress];
delete claimRequest[hashAddress];
//address hashSwap = _getHashAddress(getPairByID[c.pairID].tokenB, getPairByID[c.pairID].tokenA, c.sender, c.receiver);
uint256 balance = _balanceOf[hashAddress]; // swapped amount of foreign tokens (include current claim amount)
uint256 amount = uint256(c.amount); // amount of foreign token to swap
require (amount != 0, "No active claim request");
require(foreignBalance == c.foreignBalance, "Oracle error");
uint256 nativeAmount;
uint256 rest;
if (foreignBalance >= balance) {
//approve, user deposited not less foreign tokens then want to swap
uint256 pairID = uint256(c.pairID);
(uint256 nativeRate, uint256 nativeSpent) = _decode(nativeEncoded);
(nativeAmount, rest) = _calculateAmount(
pairID,
amount,
uint256(c.currentRate),
foreignSpent,
nativeSpent,
nativeRate
);
if (rest != 0) {
_balanceOf[hashAddress] = balance - rest; // not all amount swapped
amount = amount - rest; // swapped amount
}
require(totalSupply[pairID] >= nativeAmount, "Not enough Total Supply"); // may be commented
totalSupply[pairID] = totalSupply[pairID] - nativeAmount;
if (c.isInvestment)
_contributeFromSmartSwap(getPairByID[pairID].tokenA, c.receiver, c.sender, nativeAmount);
else
_transfer(getPairByID[pairID].tokenA, c.receiver, nativeAmount);
} else {
//disapprove, discard claim
_balanceOf[hashAddress] = balance - amount;
amount = 0;
}
emit ClaimApprove(hashAddress, c.claimID, nativeAmount, amount, c.isInvestment);
}
// use structure to avoid stack too deep
struct CalcVariables {
// 18 decimals nominator with decimals converter:
// Foreign = Native * Rate(18) / nominatorNativeToForeign
uint256 nominatorForeignToNative; // 10**(18 + foreign decimals - native decimals)
uint256 nominatorNativeToForeign; // 10**(18 + native decimals - foreign decimals)
uint256 localNative; // already swapped Native tokens = _balanceOf[hashNative]
uint256 localForeign; // already swapped Foreign tokens = decoded _balanceOf[hashForeign]
uint256 localForeignRate; // Foreign token price / Native token price = decoded _balanceOf[hashForeign]
address hashNative; // _getHashAddress(tokenA, tokenB, address(0), address(0));
address hashForeign; // _getHashAddress(tokenB, tokenA, address(0), address(0));
}
function _calculateAmount(
uint256 pairID,
uint256 foreignAmount,
uint256 rate, // Foreign token price / Native token price = (Native amount / Foreign amount)
uint256 foreignSpent, // already swapped Foreign tokens (got from foreign contract)
uint256 nativeSpent, // already swapped Native tokens (got from foreign contract)
uint256 nativeRate // Native token price / Foreign token price. I.e. on BSC side: BNB price / ETH price = 0.2
)
internal
returns(uint256 nativeAmount, uint256 rest)
{
CalcVariables memory vars;
{
address tokenA = getPairByID[pairID].tokenA;
address tokenB = getPairByID[pairID].tokenB;
uint256 nativeDecimals = decimals[tokenA];
uint256 foreignDecimals = decimals[tokenB];
vars.nominatorForeignToNative = 10**(18+foreignDecimals-nativeDecimals);
vars.nominatorNativeToForeign = 10**(18+nativeDecimals-foreignDecimals);
vars.hashNative = _getHashAddress(tokenA, tokenB, address(0), address(0));
vars.hashForeign = _getHashAddress(tokenB, tokenA, address(0), address(0));
vars.localNative = _balanceOf[vars.hashNative];
(vars.localForeignRate, vars.localForeign) = _decode(_balanceOf[vars.hashForeign]);
}
// step 1. Check is it enough unspent native tokens
{
require(nativeSpent >= vars.localNative, "NativeSpent balance higher then remote");
uint256 nativeAvailable = nativeSpent - vars.localNative;
// nativeAvailable - amount ready to spend native tokens
// nativeRate = Native token price / Foreign token price. I.e. on BSC side BNB price / ETH price = 0.2
if (nativeAvailable != 0) {
// ?
uint256 requireAmount = foreignAmount * vars.nominatorNativeToForeign / nativeRate;
if (requireAmount <= nativeAvailable) {
nativeAmount = requireAmount; // use already swapped tokens
foreignAmount = 0;
}
else {
nativeAmount = nativeAvailable;
foreignAmount = (requireAmount - nativeAvailable) * nativeRate / vars.nominatorNativeToForeign;
}
_balanceOf[vars.hashNative] += nativeAmount;
}
}
require(totalSupply[pairID] >= nativeAmount,"ERR: Not enough Total Supply");
// step 2. recalculate rate for swapped tokens
if (foreignAmount != 0) {
// i.e. on BSC side: rate = ETH price / BNB price = 5
uint256 requireAmount = foreignAmount * rate / vars.nominatorForeignToNative;
if (totalSupply[pairID] < nativeAmount + requireAmount) {
requireAmount = totalSupply[pairID] - nativeAmount;
rest = foreignAmount - (requireAmount * vars.nominatorForeignToNative / rate);
foreignAmount = foreignAmount - rest;
}
nativeAmount = nativeAmount + requireAmount;
require(vars.localForeign >= foreignSpent, "ForeignSpent balance higher then local");
uint256 foreignAvailable = vars.localForeign - foreignSpent;
// vars.localForeignRate, foreignAvailable - rate and amount swapped foreign tokens
if (foreignAvailable != 0) { // recalculate avarage rate (native amount / foreign amount)
rate = ((foreignAvailable * vars.localForeignRate) + (requireAmount * vars.nominatorForeignToNative)) / (foreignAvailable + foreignAmount);
}
_balanceOf[vars.hashForeign] = _encode(rate, vars.localForeign + foreignAmount);
}
}
// transfer fee to receiver and request SMART token as compensation.
// tokenA - token that user send
// amount - amount of tokens that user send
// user - address of user
function _transferFee(address tokenA, uint256 amount, address user, address licensee) internal {
require(licensee == address(0) || licenseeCompensator[licensee] != address(0), "licensee is not registered");
uint256 feeAmount = msg.value;
uint256 compFee; // company fee
if (tokenA < NATIVE_COINS) {
require(feeAmount >= amount, "Insuficiant value"); // if native coin, then feeAmount = msg.value - swap amount
feeAmount -= amount;
compFee = amount * companyFee / 10000; // company fee
}
require(feeAmount >= processingFee, "Insufficient processing fee");
uint256 otherFee = feeAmount - processingFee;
uint256 licenseeFeeAmount;
uint256 licenseeFeeRate = licenseeFee[licensee];
if (licenseeFeeRate != 0 && otherFee != 0) {
if (tokenA < NATIVE_COINS) {
licenseeFeeAmount = amount * licenseeFeeRate / 10000;
} else {
licenseeFeeAmount = (otherFee * licenseeFeeRate)/(licenseeFeeRate + companyFee);
}
}
require(otherFee >= compFee + licenseeFeeAmount, "Insuficiant fee");
feeAmount -= licenseeFeeAmount;
if (licenseeFeeAmount != 0) {
TransferHelper.safeTransferETH(licensee, licenseeFeeAmount);
ISmart(licenseeCompensator[licensee]).requestCompensation(user, licenseeFeeAmount);
}
//TransferHelper.safeTransferETH(feeReceiver, feeAmount);
collectedFees += feeAmount;
if(contractSmart != address(0) && !isExcludedSender[msg.sender]) {
feeAmount = ((feeAmount - processingFee) * companyFeeReimbursement + processingFee * swapGasReimbursement) / 100;
if (feeAmount != 0)
ISmart(contractSmart).requestCompensation(user, feeAmount);
}
}
// contribute from SmartSwap on user behalf
function _contributeFromSmartSwap(address token, address to, address user, uint256 value) internal {
if (token < NATIVE_COINS) {
IAuction(to).contributeFromSmartSwap{value: value}(payable(user));
} else {
IERC20(token).approve(to, value);
IAuction(to).contributeFromSmartSwap(token, value, user);
}
}
// call appropriate transfer function
function _transfer(address token, address to, uint256 value) internal {
if (token < NATIVE_COINS)
TransferHelper.safeTransferETH(to, value);
else
TransferHelper.safeTransfer(token, to, value);
}
// encode 64 bits of rate (decimal = 9). and 192 bits of amount
// into uint256 where high 64 bits is rate and low 192 bit is amount
// rate = foreign token price / native token price
function _encode(uint256 rate, uint256 amount) internal pure returns(uint256 encodedBalance) {
require(amount < MAX_AMOUNT, "Amount overflow");
require(rate < MAX_AMOUNT, "Rate overflow");
encodedBalance = rate * MAX_AMOUNT + amount;
}
// decode from uint256 where high 64 bits is rate and low 192 bit is amount
// rate = foreign token price / native token price
function _decode(uint256 encodedBalance) internal pure returns(uint256 rate, uint256 amount) {
rate = encodedBalance / MAX_AMOUNT;
amount = uint128(encodedBalance);
}
function _getHashAddress(
address tokenA,
address tokenB,
address sender,
address receiver
)
internal
pure
returns (address)
{
return address(uint160(uint256(keccak256(abi.encodePacked(tokenA, tokenB, sender, receiver)))));
}
} | return balance for swap | function getBalance(
address tokenA,
address tokenB,
address sender,
address receiver
)
external
view
returns (uint256)
{
return _balanceOf[_getHashAddress(tokenA, tokenB, sender, receiver)];
}
| 285,084 |
./partial_match/42/0xa5e044bB1025d095782DDccfD70eA17EA6EA76c5/sources/CollateralManager.sol | Remove it from the the address set lib. | function removePynths(bytes32[] calldata pynths, bytes32[] calldata synthKeys) external onlyOwner {
for (uint i = 0; i < pynths.length; i++) {
if (_pynths.contains(pynths[i])) {
_pynths.remove(pynths[i]);
delete pynthsByKey[synthKeys[i]];
emit PynthRemoved(pynths[i]);
}
}
}
| 8,831,512 |
// File: localhost/Toft_Contracts/contracts/ToftToken/openzeppelin/utils/Pausable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/**
* @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;
}
}
/**
* @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 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 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));
}
}
/*
* @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;
}
}
/**
* @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 {
/**
* @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 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());
}
}
/**
* @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);
}
/**
* @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 virtual view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public virtual 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 { }
}
/**
* @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");
}
}
/**
* @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 {
/**
* @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);
}
}
/**
* @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());
}
}
}
/**
* @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;
}
}
interface ITST {
/**
* @dev sets existing feeAccount to `feeAccount` by the caller.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits an {FeeAccountUpdated} event indicating the new FeeAccount.
*/
function setFeeAccount(address feeAccount) external returns (bool);
/**
* @dev sets existing maxTransferFee to `_maxTransferFee` by the caller.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits an {MaxTransferFeeUpdated} event indicating the new maximum transfer fee.
*/
function setMaxTransferFee(uint256 maxTransferFee) external returns (bool);
/**
* @dev sets existing minTransferFee to `_minTransferFee` by the caller.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits an {MinTransferFeeUpdated} event indicating the new minimum transfer fee.
*/
function setMinTransferFee(uint256 minTransferFee) external returns (bool);
/**
* @dev sets existing transferFeePercentage to `_transferFeePercentage` by the caller.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits an {TransferFeePercentageUpdated} event indicating the new percentange transfer fee.
*/
function setTransferFeePercentage(uint256 transferFeePercentage) external returns (bool);
/**
* @dev calculate transfer fee aginst `weiAmount`.
* @param weiAmount Value in wei to be to calculate fee.
* @return Number of tokens in wei to paid for transfer fee.
*/
function calculateTransferFee(uint256 weiAmount) external view returns(uint256) ;
/**
* @return the current fee account collector.
*/
function feeAccount() external view returns (address);
/**
* @return the current maximum transfer fee.
*/
function maxTransferFee() external view returns (uint256);
/**
* @return the current minimum transfer fee.
*/
function minTransferFee() external view returns (uint256);
/**
* @return the current percentange of transfer fee.
*/
function transferFeePercentage() external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient` with a transaction note `message`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount, string calldata message) 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, string calldata message) external returns (bool);
/**
* emit once on contract creatsion
*/
event Created();
/**
* Event for FeeAccount update.
* @param newFeeAccount new FeeAccount.
* @param previousFeeAccount old FeeAccount.
*/
event FeeAccountUpdated(address indexed previousFeeAccount, address indexed newFeeAccount);
/**
* Event for MaxTransferFee update.
* @param newMaxTransferFee new maximum tranfer fee.
* @param previousMaxTransferFee old maximum tranfer fee.
*/
event MaxTransferFeeUpdated(uint256 previousMaxTransferFee, uint256 newMaxTransferFee);
/**
* Event for MinTransferFee update.
* @param newMinTransferFee new minimum tranfer fee.
* @param previousMinTransferFee old minimum tranfer fee.
*/
event MinTransferFeeUpdated(uint256 previousMinTransferFee, uint256 newMinTransferFee);
/**
* Event for TransferFeePercentage update.
* @param newTransferFeePercentage new percentange tranfer fee.
* @param previousTransferFeePercentage old percentange tranfer fee.
*/
event TransferFeePercentageUpdated(uint256 previousTransferFeePercentage, uint256 newTransferFeePercentage);
/**
* @dev emitted with token transfer is done.
* @param from the account from which tokens are moved.
* @param to the recipient of tokens.
* @param value the amount to tokens moved.
* @param fee the account to fee deducted from `from`.
* @param timestamp current block timestamp.
*/
event Transfer(address indexed from, address indexed to, uint256 value, uint256 fee, string description, uint256 timestamp);
}
/*
* TransferFee
* Base contract for trasfer fee specification.
*/
abstract contract TransferFee is Ownable, ITST {
address private _feeAccount;
uint256 private _maxTransferFee;
uint256 private _minTransferFee;
uint256 private _transferFeePercentage;
/**
* @dev Constructor, _feeAccount that collects tranfer fee, fee percentange, maximum, minimum amount of wei for trasfer fee.
* @param feeAccount account that collects fee.
* @param minTransferFee Min amount of wei to be charged on trasfer.
* @param minTransferFee Min amount of wei to be charged on trasfer.
* @param transferFeePercentage Percent amount of wei to be charged on trasfer.
*/
constructor (address feeAccount, uint256 maxTransferFee, uint256 minTransferFee, uint256 transferFeePercentage) public {
require(feeAccount != address(0x0), "TransferFee: feeAccount is 0");
// this also handles "minTransferFee should be less than maxTransferFee"
// solhint-disable-next-line max-line-length
require(maxTransferFee >= minTransferFee, "TransferFee: maxTransferFee should be greater than minTransferFee");
_feeAccount = feeAccount;
_maxTransferFee = maxTransferFee;
_minTransferFee = minTransferFee;
_transferFeePercentage = transferFeePercentage;
}
/**
* See {ITrasnferFee-setFeeAccount}.
*
* @dev sets `feeAccount` to `_feeAccount` by the caller.
*
* Requirements:
*
* - `feeAccount` cannot be the zero.
*/
function setFeeAccount(address feeAccount) override external onlyOwner returns (bool) {
require(feeAccount != address(0x0), "TransferFee: feeAccount is 0");
emit FeeAccountUpdated(_feeAccount, feeAccount);
_feeAccount = feeAccount;
return true;
}
/**
* See {ITrasnferFee-setMaxTransferFee}.
*
* @dev sets `maxTransferFee` to `_maxTransferFee` by the caller.
*
* Requirements:
*
* - `maxTransferFee` cannot be the zero.
* - `maxTransferFee` should be greater than minTransferFee.
*/
function setMaxTransferFee(uint256 maxTransferFee) override external onlyOwner returns (bool) {
// solhint-disable-next-line max-line-length
require(maxTransferFee >= _minTransferFee, "TransferFee: maxTransferFee should be greater or equal to minTransferFee");
emit MaxTransferFeeUpdated(_maxTransferFee, maxTransferFee);
_maxTransferFee = maxTransferFee;
return true;
}
/**
* See {ITrasnferFee-setMinTransferFee}.
*
* @dev sets `minTransferFee` to `_minTransferFee` by the caller.
*
* Requirements:
*
* - `minTransferFee` cannot be the zero.
* - `minTransferFee` should be less than maxTransferFee.
*/
function setMinTransferFee(uint256 minTransferFee) override external onlyOwner returns (bool) {
// solhint-disable-next-line max-line-length
require(minTransferFee <= _maxTransferFee, "TransferFee: minTransferFee should be less than maxTransferFee");
emit MaxTransferFeeUpdated(_minTransferFee, minTransferFee);
_minTransferFee = minTransferFee;
return true;
}
/**
* See {ITrasnferFee-setTransferFeePercentage}.
*
* @dev sets `transferFeePercentage` to `_transferFeePercentage` by the caller.
*
* Requirements:
*
* - `transferFeePercentage` cannot be the zero.
* - `transferFeePercentage` should be less than maxTransferFee.
*/
function setTransferFeePercentage(uint256 transferFeePercentage) override external onlyOwner returns (bool) {
emit TransferFeePercentageUpdated(_transferFeePercentage, transferFeePercentage);
_transferFeePercentage = transferFeePercentage;
return true;
}
/**
* @dev See {ITrasnferFee-feeAccount}.
*/
function feeAccount() override public view returns (address) {
return _feeAccount;
}
/**
* See {ITrasnferFee-maxTransferFee}.
*/
function maxTransferFee() override public view returns (uint256) {
return _maxTransferFee;
}
/**
* See {ITrasnferFee-minTransferFee}.
*/
function minTransferFee() override public view returns (uint256) {
return _minTransferFee;
}
/**
* See {ITrasnferFee-transferFeePercentage}.
*/
function transferFeePercentage() override public view returns (uint256) {
return _transferFeePercentage;
}
}
/**
* @title Toft Standard Token
* @dev TST implementation.
*/
contract StandardToken is
Context,
Ownable,
AccessControl,
ERC20Burnable,
ERC20Pausable,
TransferFee
{
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant BURNER_ROLE = keccak256("BURNER_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,
address feeAccount,
uint256 maxTransferFee,
uint256 minTransferFee,
uint256 transferFeePercentage
)
public
TransferFee(
feeAccount,
maxTransferFee,
minTransferFee,
transferFeePercentage
)
ERC20(name, symbol)
{
_setupDecimals(2);
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
_setupRole(BURNER_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()),
"TST: must have minter role to mint"
);
require(
to == owner(),
"TST: tokens can be only minted on owner address"
);
_mint(to, amount);
}
/**
* @dev overloading burn function to enable token burn from any account
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(address account, uint256 amount) public virtual {
require(
hasRole(BURNER_ROLE, _msgSender()),
"TST: must have burner role to burn"
);
_burn(account, 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()),
"TST: 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()),
"TST: 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);
}
/**
* @dev override IERC20-transfer to deducted transfer fee from `amount`
* @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(ERC20)
returns (bool)
{
require(
recipient != address(this),
"ERC20: transfer to the this contract"
);
uint256 _fee = calculateTransferFee(amount);
// calling ERC20 transfer function to transfer tokens
super.transfer(recipient, amount);
// TST
if (_fee > 0) super.transfer(feeAccount(), _fee); // transfering fee to fee account
emit Transfer(_msgSender(), recipient, amount, _fee, "", now);
return true;
}
/**
* @dev overriding version of ${transfer} that includes message in token transfer
*
*/
function transfer(
address recipient,
uint256 amount,
string calldata message
) public virtual override(ITST) returns (bool) {
require(
recipient != address(this),
"ERC20: transfer to the this contract"
);
uint256 _fee = calculateTransferFee(amount);
// calling ERC20 transfer function to transfer tokens
super.transfer(recipient, amount);
// TST
if (_fee > 0) super.transfer(feeAccount(), _fee); // transfering fee to fee account
emit Transfer(_msgSender(), recipient, amount, _fee, message, now);
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(ERC20) returns (bool) {
require(
recipient != address(this),
"ERC20: transfer to the this contract"
);
uint256 _fee = calculateTransferFee(amount);
// calling ERC20 transfer function to transfer tokens
super.transferFrom(sender, recipient, amount);
// TST
if (_fee > 0) super.transferFrom(sender, feeAccount(), _fee); // transfering fee to fee account
emit Transfer(sender, recipient, amount, _fee, "", now);
return true;
}
/**
* @dev overriding version of ${transferFrom} that includes message in token transfer
*
*/
function transferFrom(
address sender,
address recipient,
uint256 amount,
string calldata message
) public virtual override(ITST) returns (bool) {
require(
recipient != address(this),
"ERC20: transfer to the this contract"
);
uint256 _fee = calculateTransferFee(amount);
// calling ERC20 transfer function to transfer tokens
super.transferFrom(sender, recipient, amount);
// TST
if (_fee > 0) super.transferFrom(sender, feeAccount(), _fee); // transfering fee to fee account
emit Transfer(sender, recipient, amount, _fee, message, now);
return true;
}
/**
* @dev calculate transfer fee aginst `weiAmount`.
* @param weiAmount Value in wei to be to calculate fee.
* @return Number of tokens in wei to paid for transfer fee.
*/
function calculateTransferFee(uint256 weiAmount)
public
virtual
override(ITST)
view
returns (uint256)
{
uint256 divisor = uint256(100).mul((10**uint256(decimals())));
uint256 _fee = (transferFeePercentage().mul(weiAmount)).div(divisor);
if (_fee < minTransferFee()) {
_fee = minTransferFee();
} else if (_fee > maxTransferFee()) {
_fee = maxTransferFee();
}
return _fee;
}
/**
* @dev See {IERC20-totalSupply}.
* @return the current supply of tokens.
*
* Requirements:
*
* - the caller must have the {Owner}.
*/
function totalSupply()
public
virtual
override(ERC20)
view
onlyOwner
returns (uint256)
{
return super.totalSupply();
}
// TOFT: THESE FUNCTIONS ARE ADDED TO MAKE THIS CONTRACT COMPATIBLE WITH EXISTING APPS
function increaseSupply(address target, uint256 amount) external virtual {
mint(target, amount);
}
function decreaseSupply(address target, uint256 amount) external virtual {
burn(target, amount);
}
function getOwner() external view returns (address) {
return owner();
}
function getName() external view returns (string memory) {
return name();
}
function getFeeAccount() external view returns (address) {
return feeAccount();
}
function getTotalSupply() external view returns (uint256) {
return totalSupply();
}
function getMaxTransferFee() external view returns (uint256) {
return maxTransferFee();
}
function getMinTransferFee() external view returns (uint256) {
return minTransferFee();
}
function getTransferFeePercentage() external view returns (uint256) {
return transferFeePercentage();
}
function getBalance(address balanceAddress)
external
virtual
view
returns (uint256)
{
return balanceOf(balanceAddress);
}
}
abstract contract UpgradedStandardToken is StandardToken {
// those methods are called by the legacy contract
// and they must ensure msg.sender to be the contract address
function transferByLegacy(
address from,
address recipient,
uint256 amount
) public virtual returns (bool);
function transferByLegacy(
address from,
address recipient,
uint256 amount,
string calldata message
) external virtual returns (bool);
function transferFromByLegacy(
address sender,
address from,
address recipient,
uint256 amount
) external virtual returns (bool);
function transferFromByLegacy(
address sender,
address from,
address recipient,
uint256 amount,
string calldata message
) external virtual returns (bool);
function approveByLegacy(
address from,
address spender,
uint256 amount
) external virtual returns (bool);
function totalSupplyByLegacy() external virtual view returns (uint256);
}
contract TST is StandardToken {
address public upgradedAddress;
bool public deprecated;
// Called when contract is deprecated
event Deprecate(address newAddress);
constructor(
string memory name,
string memory symbol,
address feeAccount,
uint256 maxTransferFee,
uint256 minTransferFee,
uint256 transferFeePercentage
)
public
StandardToken(
name,
symbol,
feeAccount,
maxTransferFee,
minTransferFee,
transferFeePercentage
)
{
deprecated = false;
}
// Forward StandardToken methods to upgraded contract if this one is deprecated
function mint(address to, uint256 amount) public override(StandardToken) {
if (!deprecated) return super.mint(to, amount);
else return UpgradedStandardToken(upgradedAddress).mint(to, amount);
}
// Forward StandardToken methods to upgraded contract if this one is deprecated
function burn(address account, uint256 amount)
public
override(StandardToken)
{
if (!deprecated) return super.burn(account, amount);
else
return UpgradedStandardToken(upgradedAddress).burn(account, amount);
}
// Forward StandardToken methods to upgraded contract if this one is deprecated
function pause() public override(StandardToken) {
if (!deprecated) return super.pause();
else return UpgradedStandardToken(upgradedAddress).pause();
}
// Forward StandardToken methods to upgraded contract if this one is deprecated
function unpause() public override(StandardToken) {
if (!deprecated) return super.unpause();
else return UpgradedStandardToken(upgradedAddress).unpause();
}
// Forward StandardToken methods to upgraded contract if this one is deprecated
function transfer(address recipient, uint256 amount)
public
override(StandardToken)
returns (bool)
{
if (!deprecated) return super.transfer(recipient, amount);
else
return
UpgradedStandardToken(upgradedAddress).transferByLegacy(
msg.sender,
recipient,
amount
);
}
// Forward StandardToken methods to upgraded contract if this one is deprecated
function transfer(
address recipient,
uint256 amount,
string calldata message
) public override(StandardToken) returns (bool) {
if (!deprecated) return super.transfer(recipient, amount, message);
else
return
UpgradedStandardToken(upgradedAddress).transferByLegacy(
msg.sender,
recipient,
amount,
message
);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override(StandardToken) returns (bool) {
if (!deprecated) return super.transferFrom(sender, recipient, amount);
else
return
UpgradedStandardToken(upgradedAddress).transferFromByLegacy(
msg.sender,
sender,
recipient,
amount
);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(
address sender,
address recipient,
uint256 amount,
string calldata message
) public override(StandardToken) returns (bool) {
if (!deprecated)
return super.transferFrom(sender, recipient, amount, message);
else
return
UpgradedStandardToken(upgradedAddress).transferFromByLegacy(
msg.sender,
sender,
recipient,
amount,
message
);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function balanceOf(address account) public override view returns (uint256) {
if (!deprecated) return super.balanceOf(account);
else return UpgradedStandardToken(upgradedAddress).balanceOf(account);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function totalSupply() public override view returns (uint256) {
if (!deprecated) return super.totalSupply();
else return UpgradedStandardToken(upgradedAddress).totalSupplyByLegacy();
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function approve(address spender, uint256 amount)
public
override(ERC20)
returns (bool)
{
if (!deprecated) return super.approve(spender, amount);
else
return
UpgradedStandardToken(upgradedAddress).approveByLegacy(
msg.sender,
spender,
amount
);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function allowance(address owner, address spender)
public
override(ERC20)
view
returns (uint256)
{
if (!deprecated) return super.allowance(owner, spender);
else
return
UpgradedStandardToken(upgradedAddress).allowance(
owner,
spender
);
}
// deprecate current contract in favour of a new one
function deprecate(address _upgradedAddress) public onlyOwner {
deprecated = true;
upgradedAddress = _upgradedAddress;
Deprecate(_upgradedAddress);
}
function increaseSupply(address target, uint256 amount)
external
override(StandardToken)
{
mint(target, amount);
}
function decreaseSupply(address target, uint256 amount)
external
override(StandardToken)
{
burn(target, amount);
}
function getBalance(address balanceAddress)
external
override
view
returns (uint256)
{
return balanceOf(balanceAddress);
}
} | See {ITrasnferFee-setMinTransferFee}. sets `minTransferFee` to `_minTransferFee` by the caller. Requirements: - `minTransferFee` cannot be the zero. - `minTransferFee` should be less than maxTransferFee./ solhint-disable-next-line max-line-length | function setMinTransferFee(uint256 minTransferFee) override external onlyOwner returns (bool) {
require(minTransferFee <= _maxTransferFee, "TransferFee: minTransferFee should be less than maxTransferFee");
emit MaxTransferFeeUpdated(_minTransferFee, minTransferFee);
_minTransferFee = minTransferFee;
return true;
}
| 2,277,815 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title: MinteVipTicket
/// @authors: manifold.xyz & Collector
import "./ERC721Creator.sol";
contract MVIP is ERC721Creator {
uint256 public price = 40000000000000000; //0.04 ETH
bool public saleIsActive = true;
uint private rand;
constructor(string memory tokenName, string memory symbol) ERC721Creator(tokenName, symbol) {}
/* claim multiple tokens */
function claimBatch(address to, uint256 _qty) public nonReentrant payable {
require(_qty > 0, "Quantity must be more than 0");
require(saleIsActive, "Sale must be active to mint");
require(msg.value >= price*_qty, "Price is not correct.");
string memory uri;
for (uint i = 0; i < _qty; i++) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
rand = (pseudo_rand()%100)+1;
uri = getVIPUri(rand);
_mintBase(to, uri);
}
}
function getVIPUri(uint r) private pure returns (string memory) {
string memory uri;
if (r < 41 ){
uri = "ipfs://QmTfFj2d8oXRRhmFG9h82zkSdTjzEiqk3ZCiotFp2XLtfg"; //DYNASTY
} else if (r >= 41 && r < 69){
uri = "ipfs://QmYXwKTQRutEgMyjP35kcSqvZ6mZnB92Q4Hgu7LnVvLD4j"; //RELICS
} else if (r >= 69 && r < 86){
uri = "ipfs://QmW7us4Zmk9ZcZQVgR17QijKCXFMFCXvtLxwSL9gFFFL6y"; //ROYALS
} else if (r >= 86 && r < 96){
uri = "ipfs://QmR2LJjd7hCm95FFtVvgxz8f98LKLTQeXgHdWqHiwnToQR"; //LEGENDS
} else if (r >= 96 && r < 100){
uri = "ipfs://QmYtD7m8mUb3JHwQCEaskjW9KPwrr2XgQNnFEwjLnnEzkC"; //COSMOS
} else {
uri = "ipfs://QmQDAGCT5ux1Fc6zTKjbVNF18KofYpLDTK7AiRN3P5dP4C"; //GENESIS
}
return uri;
}
function pseudo_rand() private view returns (uint) {
return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, _tokenCount)));
}
function withdraw() public payable adminRequired {
require(payable(_msgSender()).send(address(this).balance));
}
function changeSaleState() public adminRequired {
saleIsActive = !saleIsActive;
}
function changePrice(uint256 newPrice) public adminRequired {
price = newPrice;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "./access/AdminControl.sol";
import "./core/ERC721CreatorCore.sol";
/**
* @dev ERC721Creator implementation
*/
contract ERC721Creator is AdminControl, ERC721, ERC721CreatorCore {
constructor (string memory _name, string memory _symbol) ERC721(_name, _symbol) {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721CreatorCore, AdminControl) returns (bool) {
return ERC721CreatorCore.supportsInterface(interfaceId) || ERC721.supportsInterface(interfaceId) || AdminControl.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
_approveTransfer(from, to, tokenId);
}
/**
* @dev See {ICreatorCore-registerExtension}.
*/
function registerExtension(address extension, string calldata baseURI) external override adminRequired nonBlacklistRequired(extension) {
_registerExtension(extension, baseURI, false);
}
/**
* @dev See {ICreatorCore-registerExtension}.
*/
function registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) external override adminRequired nonBlacklistRequired(extension) {
_registerExtension(extension, baseURI, baseURIIdentical);
}
/**
* @dev See {ICreatorCore-unregisterExtension}.
*/
function unregisterExtension(address extension) external override adminRequired {
_unregisterExtension(extension);
}
/**
* @dev See {ICreatorCore-blacklistExtension}.
*/
function blacklistExtension(address extension) external override adminRequired {
_blacklistExtension(extension);
}
/**
* @dev See {ICreatorCore-setBaseTokenURIExtension}.
*/
function setBaseTokenURIExtension(string calldata uri) external override extensionRequired {
_setBaseTokenURIExtension(uri, false);
}
/**
* @dev See {ICreatorCore-setBaseTokenURIExtension}.
*/
function setBaseTokenURIExtension(string calldata uri, bool identical) external override extensionRequired {
_setBaseTokenURIExtension(uri, identical);
}
/**
* @dev See {ICreatorCore-setTokenURIPrefixExtension}.
*/
function setTokenURIPrefixExtension(string calldata prefix) external override extensionRequired {
_setTokenURIPrefixExtension(prefix);
}
/**
* @dev See {ICreatorCore-setTokenURIExtension}.
*/
function setTokenURIExtension(uint256 tokenId, string calldata uri) external override extensionRequired {
_setTokenURIExtension(tokenId, uri);
}
/**
* @dev See {ICreatorCore-setTokenURIExtension}.
*/
function setTokenURIExtension(uint256[] memory tokenIds, string[] calldata uris) external override extensionRequired {
require(tokenIds.length == uris.length, "Invalid input");
for (uint i = 0; i < tokenIds.length; i++) {
_setTokenURIExtension(tokenIds[i], uris[i]);
}
}
/**
* @dev See {ICreatorCore-setBaseTokenURI}.
*/
function setBaseTokenURI(string calldata uri) external override adminRequired {
_setBaseTokenURI(uri);
}
/**
* @dev See {ICreatorCore-setTokenURIPrefix}.
*/
function setTokenURIPrefix(string calldata prefix) external override adminRequired {
_setTokenURIPrefix(prefix);
}
/**
* @dev See {ICreatorCore-setTokenURI}.
*/
function setTokenURI(uint256 tokenId, string calldata uri) external override adminRequired {
_setTokenURI(tokenId, uri);
}
/**
* @dev See {ICreatorCore-setTokenURI}.
*/
function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external override adminRequired {
require(tokenIds.length == uris.length, "Invalid input");
for (uint i = 0; i < tokenIds.length; i++) {
_setTokenURI(tokenIds[i], uris[i]);
}
}
/**
* @dev See {ICreatorCore-setMintPermissions}.
*/
function setMintPermissions(address extension, address permissions) external override adminRequired {
_setMintPermissions(extension, permissions);
}
/**
* @dev See {IERC721CreatorCore-mintBase}.
*/
function mintBase(address to) public virtual override nonReentrant adminRequired returns(uint256) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
return _mintBase(to, "");
}
/**
* @dev See {IERC721CreatorCore-mintBase}.
*/
function mintBase(address to, string calldata uri) public virtual override nonReentrant adminRequired returns(uint256) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
return _mintBase(to, uri);
}
/**
* @dev See {IERC721CreatorCore-mintBaseBatch}.
*/
function mintBaseBatch(address to, uint16 count) public virtual override nonReentrant adminRequired returns(uint256[] memory tokenIds) {
tokenIds = new uint256[](count);
for (uint16 i = 0; i < count; i++) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
tokenIds[i] = _mintBase(to, "");
}
return tokenIds;
}
/**
* @dev See {IERC721CreatorCore-mintBaseBatch}.
*/
function mintBaseBatch(address to, string[] calldata uris) public virtual override nonReentrant adminRequired returns(uint256[] memory tokenIds) {
tokenIds = new uint256[](uris.length);
for (uint i = 0; i < uris.length; i++) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
tokenIds[i] = _mintBase(to, uris[i]);
}
return tokenIds;
}
/**
* @dev Mint token with no extension
*/
function _mintBase(address to, string memory uri) internal virtual returns(uint256 tokenId) {
_tokenCount++;
tokenId = _tokenCount;
// Track the extension that minted the token
_tokensExtension[tokenId] = address(this);
_safeMint(to, tokenId);
if (bytes(uri).length > 0) {
_tokenURIs[tokenId] = uri;
}
// Call post mint
_postMintBase(to, tokenId);
return tokenId;
}
/**
* @dev See {IERC721CreatorCore-mintExtension}.
*/
function mintExtension(address to) public virtual override nonReentrant extensionRequired returns(uint256) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
return _mintExtension(to, "");
}
/**
* @dev See {IERC721CreatorCore-mintExtension}.
*/
function mintExtension(address to, string calldata uri) public virtual override nonReentrant extensionRequired returns(uint256) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
return _mintExtension(to, uri);
}
/**
* @dev See {IERC721CreatorCore-mintExtensionBatch}.
*/
function mintExtensionBatch(address to, uint16 count) public virtual override nonReentrant extensionRequired returns(uint256[] memory tokenIds) {
tokenIds = new uint256[](count);
for (uint16 i = 0; i < count; i++) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
tokenIds[i] = _mintExtension(to, "");
}
return tokenIds;
}
/**
* @dev See {IERC721CreatorCore-mintExtensionBatch}.
*/
function mintExtensionBatch(address to, string[] calldata uris) public virtual override nonReentrant extensionRequired returns(uint256[] memory tokenIds) {
tokenIds = new uint256[](uris.length);
for (uint i = 0; i < uris.length; i++) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
tokenIds[i] = _mintExtension(to, uris[i]);
}
}
/**
* @dev Mint token via extension
*/
function _mintExtension(address to, string memory uri) internal virtual returns(uint256 tokenId) {
_tokenCount++;
tokenId = _tokenCount;
_checkMintPermissions(to, tokenId);
// Track the extension that minted the token
_tokensExtension[tokenId] = msg.sender;
_safeMint(to, tokenId);
if (bytes(uri).length > 0) {
_tokenURIs[tokenId] = uri;
}
// Call post mint
_postMintExtension(to, tokenId);
return tokenId;
}
/**
* @dev See {IERC721CreatorCore-tokenExtension}.
*/
function tokenExtension(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "Nonexistent token");
return _tokenExtension(tokenId);
}
/**
* @dev See {IERC721CreatorCore-burn}.
*/
function burn(uint256 tokenId) public virtual override nonReentrant {
require(_isApprovedOrOwner(msg.sender, tokenId), "Caller is not owner nor approved");
address owner = ownerOf(tokenId);
_burn(tokenId);
_postBurn(owner, tokenId);
}
/**
* @dev See {ICreatorCore-setRoyalties}.
*/
function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired {
_setRoyaltiesExtension(address(this), receivers, basisPoints);
}
/**
* @dev See {ICreatorCore-setRoyalties}.
*/
function setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired {
require(_exists(tokenId), "Nonexistent token");
_setRoyalties(tokenId, receivers, basisPoints);
}
/**
* @dev See {ICreatorCore-setRoyaltiesExtension}.
*/
function setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired {
_setRoyaltiesExtension(extension, receivers, basisPoints);
}
/**
* @dev {See ICreatorCore-getRoyalties}.
*/
function getRoyalties(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyalties(tokenId);
}
/**
* @dev {See ICreatorCore-getFees}.
*/
function getFees(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyalties(tokenId);
}
/**
* @dev {See ICreatorCore-getFeeRecipients}.
*/
function getFeeRecipients(uint256 tokenId) external view virtual override returns (address payable[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyReceivers(tokenId);
}
/**
* @dev {See ICreatorCore-getFeeBps}.
*/
function getFeeBps(uint256 tokenId) external view virtual override returns (uint[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyBPS(tokenId);
}
/**
* @dev {See ICreatorCore-royaltyInfo}.
*/
function royaltyInfo(uint256 tokenId, uint256 value, bytes calldata) external view virtual override returns (address, uint256, bytes memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyInfo(tokenId, value);
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "Nonexistent token");
return _tokenURI(tokenId);
}
}
// SPDX-License-Identifier: MIT
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}. 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 {
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 = 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 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("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
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` 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 { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./IAdminControl.sol";
abstract contract AdminControl is Ownable, IAdminControl, ERC165 {
using EnumerableSet for EnumerableSet.AddressSet;
// Track registered admins
EnumerableSet.AddressSet private _admins;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IAdminControl).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Only allows approved admins to call the specified function
*/
modifier adminRequired() {
require(owner() == msg.sender || _admins.contains(msg.sender), "AdminControl: Must be owner or admin");
_;
}
/**
* @dev See {IAdminControl-getAdmins}.
*/
function getAdmins() external view override returns (address[] memory admins) {
admins = new address[](_admins.length());
for (uint i = 0; i < _admins.length(); i++) {
admins[i] = _admins.at(i);
}
return admins;
}
/**
* @dev See {IAdminControl-approveAdmin}.
*/
function approveAdmin(address admin) external override onlyOwner {
if (!_admins.contains(admin)) {
emit AdminApproved(admin, msg.sender);
_admins.add(admin);
}
}
/**
* @dev See {IAdminControl-revokeAdmin}.
*/
function revokeAdmin(address admin) external override onlyOwner {
if (_admins.contains(admin)) {
emit AdminRevoked(admin, msg.sender);
_admins.remove(admin);
}
}
/**
* @dev See {IAdminControl-isAdmin}.
*/
function isAdmin(address admin) public override view returns (bool) {
return (owner() == admin || _admins.contains(admin));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "../extensions/ERC721/IERC721CreatorExtensionApproveTransfer.sol";
import "../extensions/ERC721/IERC721CreatorExtensionBurnable.sol";
import "../permissions/ERC721/IERC721CreatorMintPermissions.sol";
import "./IERC721CreatorCore.sol";
import "./CreatorCore.sol";
/**
* @dev Core ERC721 creator implementation
*/
abstract contract ERC721CreatorCore is CreatorCore, IERC721CreatorCore {
using EnumerableSet for EnumerableSet.AddressSet;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(CreatorCore, IERC165) returns (bool) {
return interfaceId == type(IERC721CreatorCore).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {ICreatorCore-setApproveTransferExtension}.
*/
function setApproveTransferExtension(bool enabled) external override extensionRequired {
require(!enabled || ERC165Checker.supportsInterface(msg.sender, type(IERC721CreatorExtensionApproveTransfer).interfaceId), "Extension must implement IERC721CreatorExtensionApproveTransfer");
if (_extensionApproveTransfers[msg.sender] != enabled) {
_extensionApproveTransfers[msg.sender] = enabled;
emit ExtensionApproveTransferUpdated(msg.sender, enabled);
}
}
/**
* @dev Set mint permissions for an extension
*/
function _setMintPermissions(address extension, address permissions) internal {
require(_extensions.contains(extension), "CreatorCore: Invalid extension");
require(permissions == address(0x0) || ERC165Checker.supportsInterface(permissions, type(IERC721CreatorMintPermissions).interfaceId), "Invalid address");
if (_extensionPermissions[extension] != permissions) {
_extensionPermissions[extension] = permissions;
emit MintPermissionsUpdated(extension, permissions, msg.sender);
}
}
/**
* Check if an extension can mint
*/
function _checkMintPermissions(address to, uint256 tokenId) internal {
if (_extensionPermissions[msg.sender] != address(0x0)) {
IERC721CreatorMintPermissions(_extensionPermissions[msg.sender]).approveMint(msg.sender, to, tokenId);
}
}
/**
* Override for post mint actions
*/
function _postMintBase(address, uint256) internal virtual {}
/**
* Override for post mint actions
*/
function _postMintExtension(address, uint256) internal virtual {}
/**
* Post-burning callback and metadata cleanup
*/
function _postBurn(address owner, uint256 tokenId) internal virtual {
// Callback to originating extension if needed
if (_tokensExtension[tokenId] != address(this)) {
if (ERC165Checker.supportsInterface(_tokensExtension[tokenId], type(IERC721CreatorExtensionBurnable).interfaceId)) {
IERC721CreatorExtensionBurnable(_tokensExtension[tokenId]).onBurn(owner, tokenId);
}
}
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
// Delete token origin extension tracking
delete _tokensExtension[tokenId];
}
/**
* Approve a transfer
*/
function _approveTransfer(address from, address to, uint256 tokenId) internal {
if (_extensionApproveTransfers[_tokensExtension[tokenId]]) {
require(IERC721CreatorExtensionApproveTransfer(_tokensExtension[tokenId]).approveTransfer(from, to, tokenId), "ERC721Creator: Extension approval failure");
}
}
}
// 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;
/**
* @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.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
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);
}
}
}
}
// 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) {
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.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "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] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
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
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;
/**
* @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] = 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) {
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.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 () {
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.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Interface for admin control
*/
interface IAdminControl is IERC165 {
event AdminApproved(address indexed account, address indexed sender);
event AdminRevoked(address indexed account, address indexed sender);
/**
* @dev gets address of all admins
*/
function getAdmins() external view returns (address[] memory);
/**
* @dev add an admin. Can only be called by contract owner.
*/
function approveAdmin(address admin) external;
/**
* @dev remove an admin. Can only be called by contract owner.
*/
function revokeAdmin(address admin) external;
/**
* @dev checks whether or not given address is an admin
* Returns True if they are
*/
function isAdmin(address admin) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* Implement this if you want your extension to approve a transfer
*/
interface IERC721CreatorExtensionApproveTransfer is IERC165 {
/**
* @dev Set whether or not the creator will check the extension for approval of token transfer
*/
function setApproveTransfer(address creator, bool enabled) external;
/**
* @dev Called by creator contract to approve a transfer
*/
function approveTransfer(address from, address to, uint256 tokenId) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Your extension is required to implement this interface if it wishes
* to receive the onBurn callback whenever a token the extension created is
* burned
*/
interface IERC721CreatorExtensionBurnable is IERC165 {
/**
* @dev callback handler for burn events
*/
function onBurn(address owner, uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721Creator compliant extension contracts.
*/
interface IERC721CreatorMintPermissions is IERC165 {
/**
* @dev get approval to mint
*/
function approveMint(address extension, address to, uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "./ICreatorCore.sol";
/**
* @dev Core ERC721 creator interface
*/
interface IERC721CreatorCore is ICreatorCore {
/**
* @dev mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBase(address to) external returns (uint256);
/**
* @dev mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBase(address to, string calldata uri) external returns (uint256);
/**
* @dev batch mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBaseBatch(address to, uint16 count) external returns (uint256[] memory);
/**
* @dev batch mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBaseBatch(address to, string[] calldata uris) external returns (uint256[] memory);
/**
* @dev mint a token. Can only be called by a registered extension.
* Returns tokenId minted
*/
function mintExtension(address to) external returns (uint256);
/**
* @dev mint a token. Can only be called by a registered extension.
* Returns tokenId minted
*/
function mintExtension(address to, string calldata uri) external returns (uint256);
/**
* @dev batch mint a token. Can only be called by a registered extension.
* Returns tokenIds minted
*/
function mintExtensionBatch(address to, uint16 count) external returns (uint256[] memory);
/**
* @dev batch mint a token. Can only be called by a registered extension.
* Returns tokenId minted
*/
function mintExtensionBatch(address to, string[] calldata uris) external returns (uint256[] memory);
/**
* @dev burn a token. Can only be called by token owner or approved address.
* On burn, calls back to the registered extension's onBurn method
*/
function burn(uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "../extensions/ICreatorExtensionTokenURI.sol";
import "./ICreatorCore.sol";
/**
* @dev Core creator implementation
*/
abstract contract CreatorCore is ReentrancyGuard, ICreatorCore, ERC165 {
using Strings for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
using AddressUpgradeable for address;
uint256 public _tokenCount = 0;
uint256 public MAX_TICKETS = 25000; // max number of tokens to mint
// Track registered extensions data
EnumerableSet.AddressSet internal _extensions;
EnumerableSet.AddressSet internal _blacklistedExtensions;
mapping (address => address) internal _extensionPermissions;
mapping (address => bool) internal _extensionApproveTransfers;
// For tracking which extension a token was minted by
mapping (uint256 => address) internal _tokensExtension;
// The baseURI for a given extension
mapping (address => string) private _extensionBaseURI;
mapping (address => bool) private _extensionBaseURIIdentical;
// The prefix for any tokens with a uri configured
mapping (address => string) private _extensionURIPrefix;
// Mapping for individual token URIs
mapping (uint256 => string) internal _tokenURIs;
// Royalty configurations
mapping (address => address payable[]) internal _extensionRoyaltyReceivers;
mapping (address => uint256[]) internal _extensionRoyaltyBPS;
mapping (uint256 => address payable[]) internal _tokenRoyaltyReceivers;
mapping (uint256 => uint256[]) internal _tokenRoyaltyBPS;
/**
* External interface identifiers for royalties
*/
/**
* @dev CreatorCore
*
* bytes4(keccak256('getRoyalties(uint256)')) == 0xbb3bafd6
*
* => 0xbb3bafd6 = 0xbb3bafd6
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_CREATORCORE = 0xbb3bafd6;
/**
* @dev Rarible: RoyaltiesV1
*
* bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb
* bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f
*
* => 0xb9c4d9fb ^ 0x0ebd4c7f = 0xb7799584
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584;
/**
* @dev Foundation
*
* bytes4(keccak256('getFees(uint256)')) == 0xd5a06d4c
*
* => 0xd5a06d4c = 0xd5a06d4c
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_FOUNDATION = 0xd5a06d4c;
/**
* @dev EIP-2981
*
* bytes4(keccak256("royaltyInfo(uint256,uint256,bytes)")) == 0x6057361d
*
* => 0x6057361d = 0x6057361d
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x6057361d;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(ICreatorCore).interfaceId || super.supportsInterface(interfaceId)
|| interfaceId == _INTERFACE_ID_ROYALTIES_CREATORCORE || interfaceId == _INTERFACE_ID_ROYALTIES_RARIBLE
|| interfaceId == _INTERFACE_ID_ROYALTIES_FOUNDATION || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981;
}
/**
* @dev Only allows registered extensions to call the specified function
*/
modifier extensionRequired() {
require(_extensions.contains(msg.sender), "Must be registered extension");
_;
}
/**
* @dev Only allows non-blacklisted extensions
*/
modifier nonBlacklistRequired(address extension) {
require(!_blacklistedExtensions.contains(extension), "Extension blacklisted");
_;
}
/**
* @dev See {ICreatorCore-getExtensions}.
*/
function getExtensions() external view override returns (address[] memory extensions) {
extensions = new address[](_extensions.length());
for (uint i = 0; i < _extensions.length(); i++) {
extensions[i] = _extensions.at(i);
}
return extensions;
}
/**
* @dev Register an extension
*/
function _registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) internal {
require(extension != address(this), "Creator: Invalid");
require(extension.isContract(), "Creator: Extension must be a contract");
if (!_extensions.contains(extension)) {
_extensionBaseURI[extension] = baseURI;
_extensionBaseURIIdentical[extension] = baseURIIdentical;
emit ExtensionRegistered(extension, msg.sender);
_extensions.add(extension);
}
}
/**
* @dev Unregister an extension
*/
function _unregisterExtension(address extension) internal {
if (_extensions.contains(extension)) {
emit ExtensionUnregistered(extension, msg.sender);
_extensions.remove(extension);
}
}
/**
* @dev Blacklist an extension
*/
function _blacklistExtension(address extension) internal {
require(extension != address(this), "Cannot blacklist yourself");
if (_extensions.contains(extension)) {
emit ExtensionUnregistered(extension, msg.sender);
_extensions.remove(extension);
}
if (!_blacklistedExtensions.contains(extension)) {
emit ExtensionBlacklisted(extension, msg.sender);
_blacklistedExtensions.add(extension);
}
}
/**
* @dev Set base token uri for an extension
*/
function _setBaseTokenURIExtension(string calldata uri, bool identical) internal {
_extensionBaseURI[msg.sender] = uri;
_extensionBaseURIIdentical[msg.sender] = identical;
}
/**
* @dev Set token uri prefix for an extension
*/
function _setTokenURIPrefixExtension(string calldata prefix) internal {
_extensionURIPrefix[msg.sender] = prefix;
}
/**
* @dev Set token uri for a token of an extension
*/
function _setTokenURIExtension(uint256 tokenId, string calldata uri) internal {
require(_tokensExtension[tokenId] == msg.sender, "Invalid token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Set base token uri for tokens with no extension
*/
function _setBaseTokenURI(string memory uri) internal {
_extensionBaseURI[address(this)] = uri;
}
/**
* @dev Set token uri prefix for tokens with no extension
*/
function _setTokenURIPrefix(string calldata prefix) internal {
_extensionURIPrefix[address(this)] = prefix;
}
/**
* @dev Set token uri for a token with no extension
*/
function _setTokenURI(uint256 tokenId, string calldata uri) internal {
require(_tokensExtension[tokenId] == address(this), "Invalid token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Retrieve a token's URI
*/
function _tokenURI(uint256 tokenId) internal view returns (string memory) {
address extension = _tokensExtension[tokenId];
require(!_blacklistedExtensions.contains(extension), "Extension blacklisted");
if (bytes(_tokenURIs[tokenId]).length != 0) {
if (bytes(_extensionURIPrefix[extension]).length != 0) {
return string(abi.encodePacked(_extensionURIPrefix[extension],_tokenURIs[tokenId]));
}
return _tokenURIs[tokenId];
}
if (ERC165Checker.supportsInterface(extension, type(ICreatorExtensionTokenURI).interfaceId)) {
return ICreatorExtensionTokenURI(extension).tokenURI(address(this), tokenId);
}
if (!_extensionBaseURIIdentical[extension]) {
return string(abi.encodePacked(_extensionBaseURI[extension], tokenId.toString()));
} else {
return _extensionBaseURI[extension];
}
}
/**
* Get token extension
*/
function _tokenExtension(uint256 tokenId) internal view returns (address extension) {
extension = _tokensExtension[tokenId];
require(extension != address(this), "No extension for token");
require(!_blacklistedExtensions.contains(extension), "Extension blacklisted");
return extension;
}
/**
* Helper to get royalties for a token
*/
function _getRoyalties(uint256 tokenId) view internal returns (address payable[] storage, uint256[] storage) {
return (_getRoyaltyReceivers(tokenId), _getRoyaltyBPS(tokenId));
}
/**
* Helper to get royalty receivers for a token
*/
function _getRoyaltyReceivers(uint256 tokenId) view internal returns (address payable[] storage) {
if (_tokenRoyaltyReceivers[tokenId].length > 0) {
return _tokenRoyaltyReceivers[tokenId];
} else if (_extensionRoyaltyReceivers[_tokensExtension[tokenId]].length > 0) {
return _extensionRoyaltyReceivers[_tokensExtension[tokenId]];
}
return _extensionRoyaltyReceivers[address(this)];
}
/**
* Helper to get royalty basis points for a token
*/
function _getRoyaltyBPS(uint256 tokenId) view internal returns (uint256[] storage) {
if (_tokenRoyaltyBPS[tokenId].length > 0) {
return _tokenRoyaltyBPS[tokenId];
} else if (_extensionRoyaltyBPS[_tokensExtension[tokenId]].length > 0) {
return _extensionRoyaltyBPS[_tokensExtension[tokenId]];
}
return _extensionRoyaltyBPS[address(this)];
}
function _getRoyaltyInfo(uint256 tokenId, uint256 value) view internal returns (address receiver, uint256 amount, bytes memory data){
address payable[] storage receivers = _getRoyaltyReceivers(tokenId);
require(receivers.length <= 1, "More than 1 royalty receiver");
if (receivers.length == 0) {
return (address(this), 0, data);
}
return (receivers[0], _getRoyaltyBPS(tokenId)[0]*value/10000, data);
}
/**
* Set royalties for a token
*/
function _setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) internal {
require(receivers.length == basisPoints.length, "Invalid input");
uint256 totalBasisPoints;
for (uint i = 0; i < basisPoints.length; i++) {
totalBasisPoints += basisPoints[i];
}
require(totalBasisPoints < 10000, "Invalid total royalties");
_tokenRoyaltyReceivers[tokenId] = receivers;
_tokenRoyaltyBPS[tokenId] = basisPoints;
emit RoyaltiesUpdated(tokenId, receivers, basisPoints);
}
/**
* Set royalties for all tokens of an extension
*/
function _setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) internal {
require(receivers.length == basisPoints.length, "Invalid input");
uint256 totalBasisPoints;
for (uint i = 0; i < basisPoints.length; i++) {
totalBasisPoints += basisPoints[i];
}
require(totalBasisPoints < 10000, "Invalid total royalties");
_extensionRoyaltyReceivers[extension] = receivers;
_extensionRoyaltyBPS[extension] = basisPoints;
if (extension == address(this)) {
emit DefaultRoyaltiesUpdated(receivers, basisPoints);
} else {
emit ExtensionRoyaltiesUpdated(extension, receivers, basisPoints);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Core creator interface
*/
interface ICreatorCore is IERC165 {
event ExtensionRegistered(address indexed extension, address indexed sender);
event ExtensionUnregistered(address indexed extension, address indexed sender);
event ExtensionBlacklisted(address indexed extension, address indexed sender);
event MintPermissionsUpdated(address indexed extension, address indexed permissions, address indexed sender);
event RoyaltiesUpdated(uint256 indexed tokenId, address payable[] receivers, uint256[] basisPoints);
event DefaultRoyaltiesUpdated(address payable[] receivers, uint256[] basisPoints);
event ExtensionRoyaltiesUpdated(address indexed extension, address payable[] receivers, uint256[] basisPoints);
event ExtensionApproveTransferUpdated(address indexed extension, bool enabled);
/**
* @dev gets address of all extensions
*/
function getExtensions() external view returns (address[] memory);
/**
* @dev add an extension. Can only be called by contract owner or admin.
* extension address must point to a contract implementing ICreatorExtension.
* Returns True if newly added, False if already added.
*/
function registerExtension(address extension, string calldata baseURI) external;
/**
* @dev add an extension. Can only be called by contract owner or admin.
* extension address must point to a contract implementing ICreatorExtension.
* Returns True if newly added, False if already added.
*/
function registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) external;
/**
* @dev add an extension. Can only be called by contract owner or admin.
* Returns True if removed, False if already removed.
*/
function unregisterExtension(address extension) external;
/**
* @dev blacklist an extension. Can only be called by contract owner or admin.
* This function will destroy all ability to reference the metadata of any tokens created
* by the specified extension. It will also unregister the extension if needed.
* Returns True if removed, False if already removed.
*/
function blacklistExtension(address extension) external;
/**
* @dev set the baseTokenURI of an extension. Can only be called by extension.
*/
function setBaseTokenURIExtension(string calldata uri) external;
/**
* @dev set the baseTokenURI of an extension. Can only be called by extension.
* For tokens with no uri configured, tokenURI will return "uri+tokenId"
*/
function setBaseTokenURIExtension(string calldata uri, bool identical) external;
/**
* @dev set the common prefix of an extension. Can only be called by extension.
* If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI"
* Useful if you want to use ipfs/arweave
*/
function setTokenURIPrefixExtension(string calldata prefix) external;
/**
* @dev set the tokenURI of a token extension. Can only be called by extension that minted token.
*/
function setTokenURIExtension(uint256 tokenId, string calldata uri) external;
/**
* @dev set the tokenURI of a token extension for multiple tokens. Can only be called by extension that minted token.
*/
function setTokenURIExtension(uint256[] memory tokenId, string[] calldata uri) external;
/**
* @dev set the baseTokenURI for tokens with no extension. Can only be called by owner/admin.
* For tokens with no uri configured, tokenURI will return "uri+tokenId"
*/
function setBaseTokenURI(string calldata uri) external;
/**
* @dev set the common prefix for tokens with no extension. Can only be called by owner/admin.
* If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI"
* Useful if you want to use ipfs/arweave
*/
function setTokenURIPrefix(string calldata prefix) external;
/**
* @dev set the tokenURI of a token with no extension. Can only be called by owner/admin.
*/
function setTokenURI(uint256 tokenId, string calldata uri) external;
/**
* @dev set the tokenURI of multiple tokens with no extension. Can only be called by owner/admin.
*/
function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external;
/**
* @dev set a permissions contract for an extension. Used to control minting.
*/
function setMintPermissions(address extension, address permissions) external;
/**
* @dev Configure so transfers of tokens created by the caller (must be extension) gets approval
* from the extension before transferring
*/
function setApproveTransferExtension(bool enabled) external;
/**
* @dev get the extension of a given token
*/
function tokenExtension(uint256 tokenId) external view returns (address);
/**
* @dev Set default royalties
*/
function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external;
/**
* @dev Set royalties of a token
*/
function setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) external;
/**
* @dev Set royalties of an extension
*/
function setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) external;
/**
* @dev Get royalites of a token. Returns list of receivers and basisPoints
*/
function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory);
// Royalty support for various other standards
function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory);
function getFeeBps(uint256 tokenId) external view returns (uint[] memory);
function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory);
function royaltyInfo(uint256 tokenId, uint256 value, bytes calldata data) external view returns (address, uint256, bytes memory);
}
// SPDX-License-Identifier: MIT
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 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.8.0;
import "./IERC165.sol";
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, type(IERC165).interfaceId) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) {
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
bytes memory encodedParams = abi.encodeWithSelector(IERC165(account).supportsInterface.selector, interfaceId);
(bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams);
if (result.length < 32) return false;
return success && abi.decode(result, (bool));
}
}
// 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;
// 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.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Implement this if you want your extension to have overloadable URI's
*/
interface ICreatorExtensionTokenURI is IERC165 {
/**
* Get the uri for a given creator/tokenId
*/
function tokenURI(address creator, uint256 tokenId) external view returns (string memory);
}
| See {IAdminControl-getAdmins}./ | function getAdmins() external view override returns (address[] memory admins) {
admins = new address[](_admins.length());
for (uint i = 0; i < _admins.length(); i++) {
admins[i] = _admins.at(i);
}
return admins;
}
| 6,293 |
./full_match/7701/0x4e0b416439DEe7Dc3488Eb08b408390529763AD2/sources/MagnetErc721aBase.sol | hook called after mint, used for emiting event through event hub | function _postMint() internal {
eventhub.emitMintedEvent();
}
| 13,215,318 |
./partial_match/42/0x0c3C5453c7C7a768b97d98E3Ef043f943405c38E/sources/EtherCollateralsUSD.sol | Acccount that created the loan Amount (in collateral token ) that they deposited Amount (in synths) that they issued to borrow Minting Fee When the loan was created ID for the loan When the loan was paidback (closed) Applicable Interest rate interest amounts accrued last timestamp interest amounts accrued | function aggregators(bytes32 currencyKey) external view returns (address);
function aggregatorWarningFlags() external view returns (address);
function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool);
function canFreezeRate(bytes32 currencyKey) external view returns (bool);
function currentRoundForRate(bytes32 currencyKey) external view returns (uint);
function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory);
function effectiveValue(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external view returns (uint value);
function effectiveValueAndRates(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint value,
uint sourceRate,
uint destinationRate
);
function effectiveValueAtRound(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
uint roundIdForSrc,
uint roundIdForDest
) external view returns (uint value);
function getCurrentRoundId(bytes32 currencyKey) external view returns (uint);
function getLastRoundIdBeforeElapsedSecs(
bytes32 currencyKey,
uint startingRoundId,
uint startingTimestamp,
uint timediff
) external view returns (uint);
function inversePricing(bytes32 currencyKey)
external
view
returns (
uint entryPoint,
uint upperLimit,
uint lowerLimit,
bool frozenAtUpperLimit,
bool frozenAtLowerLimit
);
function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256);
function oracle() external view returns (address);
function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time);
function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time);
function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid);
function rateForCurrency(bytes32 currencyKey) external view returns (uint);
function rateIsFlagged(bytes32 currencyKey) external view returns (bool);
function rateIsFrozen(bytes32 currencyKey) external view returns (bool);
function rateIsInvalid(bytes32 currencyKey) external view returns (bool);
function rateIsStale(bytes32 currencyKey) external view returns (bool);
function rateStalePeriod() external view returns (uint);
function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds)
external
view
returns (uint[] memory rates, uint[] memory times);
function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys)
external
view
returns (uint[] memory rates, bool anyRateInvalid);
function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory);
function freezeRate(bytes32 currencyKey) external;
}
struct SynthLoanStruct {
address payable account;
uint256 collateralAmount;
uint256 loanAmount;
uint256 mintingFee;
uint256 timeCreated;
uint256 loanID;
uint256 timeClosed;
uint256 loanInterestRate;
uint256 accruedInterest;
uint40 lastInterestAccrued;
}
bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
bytes32 private constant CONTRACT_SYNTHSUSD = "SynthsUSD";
bytes32 private constant CONTRACT_EXRATES = "ExchangeRates";
bytes32 private constant CONTRACT_FEEPOOL = "FeePool";
bytes32[24] private addressesToCache = [CONTRACT_SYSTEMSTATUS, CONTRACT_SYNTHSUSD, CONTRACT_EXRATES, CONTRACT_FEEPOOL];
public
Owned(_owner)
Pausable()
MixinResolver(_resolver, addressesToCache)
| 8,842,762 |
pragma solidity ^0.5.3;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "./interfaces/IAccounts.sol";
import "../common/Initializable.sol";
import "../common/Signatures.sol";
import "../common/UsingRegistry.sol";
import "../common/libraries/ReentrancyGuard.sol";
contract Accounts is IAccounts, Ownable, ReentrancyGuard, Initializable, UsingRegistry {
using SafeMath for uint256;
struct Signers {
// The address that is authorized to vote in governance and validator elections on behalf of the
// account. The account can vote as well, whether or not a vote signing key has been specified.
address vote;
// The address that is authorized to manage a validator or validator group and sign consensus
// messages on behalf of the account. The account can manage the validator, whether or not a
// validator signing key has been specified. However, if a validator signing key has been
// specified, only that key may actually participate in consensus.
address validator;
// The address of the key with which this account wants to sign attestations on the Attestations
// contract
address attestation;
}
struct Account {
bool exists;
// Each account may authorize signing keys to use for voting, valdiating or attestation.
// These keys may not be keys of other accounts, and may not be authorized by any other
// account for any purpose.
Signers signers;
// The address at which the account expects to receive transfers. If it's empty/0x0, the
// account indicates that an address exchange should be initiated with the dataEncryptionKey
address walletAddress;
// An optional human readable identifier for the account
string name;
// The ECDSA public key used to encrypt and decrypt data for this account
bytes dataEncryptionKey;
// The URL under which an account adds metadata and claims
string metadataURL;
}
mapping(address => Account) private accounts;
// Maps authorized signers to the account that provided the authorization.
mapping(address => address) public authorizedBy;
event AttestationSignerAuthorized(address indexed account, address signer);
event VoteSignerAuthorized(address indexed account, address signer);
event ValidatorSignerAuthorized(address indexed account, address signer);
event AttestationSignerRemoved(address indexed account, address oldSigner);
event VoteSignerRemoved(address indexed account, address oldSigner);
event ValidatorSignerRemoved(address indexed account, address oldSigner);
event AccountDataEncryptionKeySet(address indexed account, bytes dataEncryptionKey);
event AccountNameSet(address indexed account, string name);
event AccountMetadataURLSet(address indexed account, string metadataURL);
event AccountWalletAddressSet(address indexed account, address walletAddress);
event AccountCreated(address indexed account);
/**
* @notice Used in place of the constructor to allow the contract to be upgradable via proxy.
* @param registryAddress The address of the registry core smart contract.
*/
function initialize(address registryAddress) external initializer {
_transferOwnership(msg.sender);
setRegistry(registryAddress);
}
/**
* @notice Convenience Setter for the dataEncryptionKey and wallet address for an account
* @param name A string to set as the name of the account
* @param dataEncryptionKey secp256k1 public key for data encryption. Preferably compressed.
* @param walletAddress The wallet address to set for the account
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev v, r, s constitute `signer`'s signature on `msg.sender` (unless the wallet address
* is 0x0 or msg.sender).
*/
function setAccount(
string calldata name,
bytes calldata dataEncryptionKey,
address walletAddress,
uint8 v,
bytes32 r,
bytes32 s
) external {
if (!isAccount(msg.sender)) {
createAccount();
}
setName(name);
setAccountDataEncryptionKey(dataEncryptionKey);
setWalletAddress(walletAddress, v, r, s);
}
/**
* @notice Creates an account.
* @return True if account creation succeeded.
*/
function createAccount() public returns (bool) {
require(isNotAccount(msg.sender) && isNotAuthorizedSigner(msg.sender), "Account exists");
Account storage account = accounts[msg.sender];
account.exists = true;
emit AccountCreated(msg.sender);
return true;
}
/**
* @notice Setter for the name of an account.
* @param name The name to set.
*/
function setName(string memory name) public {
require(isAccount(msg.sender), "Unknown account");
Account storage account = accounts[msg.sender];
account.name = name;
emit AccountNameSet(msg.sender, name);
}
/**
* @notice Setter for the wallet address for an account
* @param walletAddress The wallet address to set for the account
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev Wallet address can be zero. This means that the owner of the wallet
* does not want to be paid directly without interaction, and instead wants users to
* contact them, using the data encryption key, and arrange a payment.
* @dev v, r, s constitute `signer`'s signature on `msg.sender` (unless the wallet address
* is 0x0 or msg.sender).
*/
function setWalletAddress(address walletAddress, uint8 v, bytes32 r, bytes32 s) public {
require(isAccount(msg.sender), "Unknown account");
if (!(walletAddress == msg.sender || walletAddress == address(0x0))) {
address signer = Signatures.getSignerOfAddress(msg.sender, v, r, s);
require(signer == walletAddress, "Invalid signature");
}
Account storage account = accounts[msg.sender];
account.walletAddress = walletAddress;
emit AccountWalletAddressSet(msg.sender, walletAddress);
}
/**
* @notice Setter for the data encryption key and version.
* @param dataEncryptionKey secp256k1 public key for data encryption. Preferably compressed.
*/
function setAccountDataEncryptionKey(bytes memory dataEncryptionKey) public {
require(dataEncryptionKey.length >= 33, "data encryption key length <= 32");
Account storage account = accounts[msg.sender];
account.dataEncryptionKey = dataEncryptionKey;
emit AccountDataEncryptionKeySet(msg.sender, dataEncryptionKey);
}
/**
* @notice Setter for the metadata of an account.
* @param metadataURL The URL to access the metadata.
*/
function setMetadataURL(string calldata metadataURL) external {
require(isAccount(msg.sender), "Unknown account");
Account storage account = accounts[msg.sender];
account.metadataURL = metadataURL;
emit AccountMetadataURLSet(msg.sender, metadataURL);
}
/**
* @notice Authorizes an address to sign votes on behalf of the account.
* @param signer The address of the signing key to authorize.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev v, r, s constitute `signer`'s signature on `msg.sender`.
*/
function authorizeVoteSigner(address signer, uint8 v, bytes32 r, bytes32 s)
external
nonReentrant
{
Account storage account = accounts[msg.sender];
authorize(signer, v, r, s);
account.signers.vote = signer;
emit VoteSignerAuthorized(msg.sender, signer);
}
/**
* @notice Authorizes an address to sign consensus messages on behalf of the account.
* @param signer The address of the signing key to authorize.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev v, r, s constitute `signer`'s signature on `msg.sender`.
*/
function authorizeValidatorSigner(address signer, uint8 v, bytes32 r, bytes32 s)
external
nonReentrant
{
Account storage account = accounts[msg.sender];
authorize(signer, v, r, s);
account.signers.validator = signer;
require(!getValidators().isValidator(msg.sender), "Cannot authorize validator signer");
emit ValidatorSignerAuthorized(msg.sender, signer);
}
/**
* @notice Authorizes an address to sign consensus messages on behalf of the account.
* @param signer The address of the signing key to authorize.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @param ecdsaPublicKey The ECDSA public key corresponding to `signer`.
* @dev v, r, s constitute `signer`'s signature on `msg.sender`.
*/
function authorizeValidatorSignerWithPublicKey(
address signer,
uint8 v,
bytes32 r,
bytes32 s,
bytes calldata ecdsaPublicKey
) external nonReentrant {
Account storage account = accounts[msg.sender];
authorize(signer, v, r, s);
account.signers.validator = signer;
require(
getValidators().updateEcdsaPublicKey(msg.sender, signer, ecdsaPublicKey),
"Failed to update ECDSA public key"
);
emit ValidatorSignerAuthorized(msg.sender, signer);
}
/**
* @notice Authorizes an address to sign consensus messages on behalf of the account.
* @param signer The address of the signing key to authorize.
* @param ecdsaPublicKey The ECDSA public key corresponding to `signer`.
* @param blsPublicKey The BLS public key that the validator is using for consensus, should pass
* proof of possession. 96 bytes.
* @param blsPop The BLS public key proof-of-possession, which consists of a signature on the
* account address. 48 bytes.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev v, r, s constitute `signer`'s signature on `msg.sender`.
*/
function authorizeValidatorSignerWithKeys(
address signer,
uint8 v,
bytes32 r,
bytes32 s,
bytes calldata ecdsaPublicKey,
bytes calldata blsPublicKey,
bytes calldata blsPop
) external nonReentrant {
Account storage account = accounts[msg.sender];
authorize(signer, v, r, s);
account.signers.validator = signer;
require(
getValidators().updatePublicKeys(msg.sender, signer, ecdsaPublicKey, blsPublicKey, blsPop),
"Failed to update validator keys"
);
emit ValidatorSignerAuthorized(msg.sender, signer);
}
/**
* @notice Authorizes an address to sign attestations on behalf of the account.
* @param signer The address of the signing key to authorize.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev v, r, s constitute `signer`'s signature on `msg.sender`.
*/
function authorizeAttestationSigner(address signer, uint8 v, bytes32 r, bytes32 s) public {
Account storage account = accounts[msg.sender];
authorize(signer, v, r, s);
account.signers.attestation = signer;
emit AttestationSignerAuthorized(msg.sender, signer);
}
/**
* @notice Removes the currently authorized vote signer for the account
*/
function removeVoteSigner() public {
Account storage account = accounts[msg.sender];
emit VoteSignerRemoved(msg.sender, account.signers.vote);
account.signers.vote = address(0);
}
/**
* @notice Removes the currently authorized validator signer for the account
*/
function removeValidatorSigner() public {
Account storage account = accounts[msg.sender];
emit ValidatorSignerRemoved(msg.sender, account.signers.validator);
account.signers.validator = address(0);
}
/**
* @notice Removes the currently authorized attestation signer for the account
*/
function removeAttestationSigner() public {
Account storage account = accounts[msg.sender];
emit AttestationSignerRemoved(msg.sender, account.signers.attestation);
account.signers.attestation = address(0);
}
/**
* @notice Returns the account associated with `signer`.
* @param signer The address of the account or currently authorized attestation signer.
* @dev Fails if the `signer` is not an account or currently authorized attestation signer.
* @return The associated account.
*/
function attestationSignerToAccount(address signer) external view returns (address) {
address authorizingAccount = authorizedBy[signer];
if (authorizingAccount != address(0)) {
require(
accounts[authorizingAccount].signers.attestation == signer,
"not active authorized attestation signer"
);
return authorizingAccount;
} else {
require(isAccount(signer), "not an account");
return signer;
}
}
/**
* @notice Returns the account associated with `signer`.
* @param signer The address of an account or currently authorized validator signer.
* @dev Fails if the `signer` is not an account or currently authorized validator.
* @return The associated account.
*/
function validatorSignerToAccount(address signer) public view returns (address) {
address authorizingAccount = authorizedBy[signer];
if (authorizingAccount != address(0)) {
require(
accounts[authorizingAccount].signers.validator == signer,
"not active authorized validator signer"
);
return authorizingAccount;
} else {
require(isAccount(signer), "not an account");
return signer;
}
}
/**
* @notice Returns the account associated with `signer`.
* @param signer The address of the account or currently authorized vote signer.
* @dev Fails if the `signer` is not an account or currently authorized vote signer.
* @return The associated account.
*/
function voteSignerToAccount(address signer) external view returns (address) {
address authorizingAccount = authorizedBy[signer];
if (authorizingAccount != address(0)) {
require(
accounts[authorizingAccount].signers.vote == signer,
"not active authorized vote signer"
);
return authorizingAccount;
} else {
require(isAccount(signer), "not an account");
return signer;
}
}
/**
* @notice Returns the account associated with `signer`.
* @param signer The address of the account or previously authorized signer.
* @dev Fails if the `signer` is not an account or previously authorized signer.
* @return The associated account.
*/
function signerToAccount(address signer) external view returns (address) {
address authorizingAccount = authorizedBy[signer];
if (authorizingAccount != address(0)) {
return authorizingAccount;
} else {
require(isAccount(signer), "Not an account");
return signer;
}
}
/**
* @notice Returns the vote signer for the specified account.
* @param account The address of the account.
* @return The address with which the account can sign votes.
*/
function getVoteSigner(address account) public view returns (address) {
require(isAccount(account), "Unknown account");
address signer = accounts[account].signers.vote;
return signer == address(0) ? account : signer;
}
/**
* @notice Returns the validator signer for the specified account.
* @param account The address of the account.
* @return The address with which the account can register a validator or group.
*/
function getValidatorSigner(address account) public view returns (address) {
require(isAccount(account), "Unknown account");
address signer = accounts[account].signers.validator;
return signer == address(0) ? account : signer;
}
/**
* @notice Returns the attestation signer for the specified account.
* @param account The address of the account.
* @return The address with which the account can sign attestations.
*/
function getAttestationSigner(address account) public view returns (address) {
require(isAccount(account), "Unknown account");
address signer = accounts[account].signers.attestation;
return signer == address(0) ? account : signer;
}
/**
* @notice Returns if account has specified a dedicated vote signer.
* @param account The address of the account.
* @return Whether the account has specified a dedicated vote signer.
*/
function hasAuthorizedVoteSigner(address account) external view returns (bool) {
require(isAccount(account));
address signer = accounts[account].signers.vote;
return signer != address(0);
}
/**
* @notice Returns if account has specified a dedicated validator signer.
* @param account The address of the account.
* @return Whether the account has specified a dedicated validator signer.
*/
function hasAuthorizedValidatorSigner(address account) external view returns (bool) {
require(isAccount(account));
address signer = accounts[account].signers.validator;
return signer != address(0);
}
/**
* @notice Returns if account has specified a dedicated attestation signer.
* @param account The address of the account.
* @return Whether the account has specified a dedicated attestation signer.
*/
function hasAuthorizedAttestationSigner(address account) external view returns (bool) {
require(isAccount(account));
address signer = accounts[account].signers.attestation;
return signer != address(0);
}
/**
* @notice Getter for the name of an account.
* @param account The address of the account to get the name for.
* @return name The name of the account.
*/
function getName(address account) external view returns (string memory) {
return accounts[account].name;
}
/**
* @notice Getter for the metadata of an account.
* @param account The address of the account to get the metadata for.
* @return metadataURL The URL to access the metadata.
*/
function getMetadataURL(address account) external view returns (string memory) {
return accounts[account].metadataURL;
}
/**
* @notice Getter for the metadata of multiple accounts.
* @param accountsToQuery The addresses of the accounts to get the metadata for.
* @return (stringLengths[] - the length of each string in bytes
* data - all strings concatenated
* )
*/
function batchGetMetadataURL(address[] calldata accountsToQuery)
external
view
returns (uint256[] memory, bytes memory)
{
uint256 totalSize = 0;
uint256[] memory sizes = new uint256[](accountsToQuery.length);
for (uint256 i = 0; i < accountsToQuery.length; i = i.add(1)) {
sizes[i] = bytes(accounts[accountsToQuery[i]].metadataURL).length;
totalSize = totalSize.add(sizes[i]);
}
bytes memory data = new bytes(totalSize);
uint256 pointer = 0;
for (uint256 i = 0; i < accountsToQuery.length; i = i.add(1)) {
for (uint256 j = 0; j < sizes[i]; j = j.add(1)) {
data[pointer] = bytes(accounts[accountsToQuery[i]].metadataURL)[j];
pointer = pointer.add(1);
}
}
return (sizes, data);
}
/**
* @notice Getter for the data encryption key and version.
* @param account The address of the account to get the key for
* @return dataEncryptionKey secp256k1 public key for data encryption. Preferably compressed.
*/
function getDataEncryptionKey(address account) external view returns (bytes memory) {
return accounts[account].dataEncryptionKey;
}
/**
* @notice Getter for the wallet address for an account
* @param account The address of the account to get the wallet address for
* @return Wallet address
*/
function getWalletAddress(address account) external view returns (address) {
return accounts[account].walletAddress;
}
/**
* @notice Check if an account already exists.
* @param account The address of the account
* @return Returns `true` if account exists. Returns `false` otherwise.
*/
function isAccount(address account) public view returns (bool) {
return (accounts[account].exists);
}
/**
* @notice Check if an account already exists.
* @param account The address of the account
* @return Returns `false` if account exists. Returns `true` otherwise.
*/
function isNotAccount(address account) internal view returns (bool) {
return (!accounts[account].exists);
}
/**
* @notice Check if an address has been an authorized signer for an account.
* @param signer The possibly authorized address.
* @return Returns `true` if authorized. Returns `false` otherwise.
*/
function isAuthorizedSigner(address signer) external view returns (bool) {
return (authorizedBy[signer] != address(0));
}
/**
* @notice Check if an address has been an authorized signer for an account.
* @param signer The possibly authorized address.
* @return Returns `false` if authorized. Returns `true` otherwise.
*/
function isNotAuthorizedSigner(address signer) internal view returns (bool) {
return (authorizedBy[signer] == address(0));
}
/**
* @notice Authorizes some role of `msg.sender`'s account to another address.
* @param authorized The address to authorize.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev Fails if the address is already authorized or is an account.
* @dev Note that once an address is authorized, it may never be authorized again.
* @dev v, r, s constitute `current`'s signature on `msg.sender`.
*/
function authorize(address authorized, uint8 v, bytes32 r, bytes32 s) private {
require(isAccount(msg.sender), "Unknown account");
require(
isNotAccount(authorized) && isNotAuthorizedSigner(authorized),
"delegate or account exists"
);
address signer = Signatures.getSignerOfAddress(msg.sender, v, r, s);
require(signer == authorized, "Invalid signature");
authorizedBy[authorized] = msg.sender;
}
}
| Removes the currently authorized attestation signer for the account/ | function removeAttestationSigner() public {
Account storage account = accounts[msg.sender];
emit AttestationSignerRemoved(msg.sender, account.signers.attestation);
account.signers.attestation = address(0);
}
| 13,126,232 |
./full_match/4/0xdFb7DA59D91246a1fe59B22fcB81F1673e257772/sources/homework/work.sol | 设置物品上下架物品必须存在必须是出借人才可以改变状态物品必须没被借出改变上下架状态 | function setGoodsStatus(string memory stickName, uint inx, bool available) public {
require(isGoodExist(stickName, inx),
"goods not exist");
require(goodsData_liuyang[stickName][inx].owner == msg.sender,
"not goods owner");
require(!goodsData_liuyang[stickName][inx].isBorrow,
"goods already lend");
goodsData_liuyang[stickName][inx].available = available;
}
| 12,388,597 |
pragma solidity 0.4.23;
/**
* @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;
}
}
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
interface tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public;
}
contract ParsecTokenERC20 {
// Public variables of the token
string public constant name = "Parsec Credits";
string public constant symbol = "PRSC";
uint8 public decimals = 6;
uint256 public initialSupply = 30856775800;
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function ParsecTokenERC20() public {
// Update total supply with the decimal amount
totalSupply = initialSupply * 10 ** uint256(decimals);
// Give the creator all initial tokens
balanceOf[msg.sender] = totalSupply;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
// Check allowance
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
// Check if the sender has enough
require(balanceOf[msg.sender] >= _value);
// Subtract from the sender
balanceOf[msg.sender] -= _value;
// Updates totalSupply
totalSupply -= _value;
// Notify clients about burned tokens
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
// Check if the targeted balance is enough
require(balanceOf[_from] >= _value);
// Check allowance
require(_value <= allowance[_from][msg.sender]);
// Subtract from the targeted balance
balanceOf[_from] -= _value;
// Subtract from the sender's allowance
allowance[_from][msg.sender] -= _value;
// Update totalSupply
totalSupply -= _value;
// Notify clients about burned tokens
Burn(_from, _value);
return true;
}
}
contract ParsecBountyCampaign is owned {
/// @notice Use OpenZeppelin's SafeMath
using SafeMath for uint256;
// ------------------------
// --- Input parameters ---
// ------------------------
/// @notice Parsec ERC20 token address (from previously deployed contract)
ParsecTokenERC20 private parsecToken;
// ---------------------------
// --- Power-up parameters ---
// ---------------------------
/// @notice Minimal amount of Parsecs to cover all bounties
uint256 public constant MINIMAL_AMOUNT_OF_PARSECS = 400000000000000; // 400,000,000.000000 PRSC
/// @notice Keep track if contract is powered up (has enough Parsecs)
bool public contractPoweredUp = false;
// ------------------------------------
// --- Bounty batch transfer state ---
// ------------------------------------
/// @notice Keep track if batch 1 / 3 is transferred
bool public batch1Transferred = false;
/// @notice Keep track if batch 2 / 3 is transferred
bool public batch2Transferred = false;
/// @notice Keep track if batch 3 / 3 is transferred
bool public batch3Transferred = false;
// ------------------------
// --- Parsecs tracking ---
// ------------------------
/// @notice Keep track of total transferred bounties
uint256 public totalTransferredBounty;
/// @notice Keep track of all transferred bounties
mapping (address => uint256) public bountyOf;
// --------------
// --- Events ---
// --------------
/// @notice Log an event for each transferred bounty
event LogCampaignBounty(address indexed sender, uint256 value, uint256 timestamp);
/**
* Constructor function
*
* Initializes smart contract
*
* @param _tokenAddress The address of the previously deployed ParsecTokenERC20 contract
*/
function ParsecBountyCampaign (address _tokenAddress) public {
// Get Parsec ERC20 token instance
parsecToken = ParsecTokenERC20(_tokenAddress);
}
/// @notice Check if contract has enough Parsecs to cover hard cap
function ownerPowerUpContract() external onlyOwner {
// Contract should not be powered up previously
require(!contractPoweredUp);
// Contract should have enough Parsec credits
require(parsecToken.balanceOf(this) >= MINIMAL_AMOUNT_OF_PARSECS);
// Raise contract power-up flag
contractPoweredUp = true;
}
/// @notice Owner can withdraw Parsecs anytime
function ownerWithdrawParsecs(uint256 value) external onlyOwner {
// Get smart contract balance in Parsecs
uint256 parsecBalance = parsecToken.balanceOf(this);
// Amount of Parsecs to withdraw should not exceed total balance in Parsecs
require(value > 0);
require(value <= parsecBalance);
// Transfer parsecs
parsecToken.transfer(owner, value);
}
/// @notice Transfer bounty batch 1 / 3
function ownerTransferBatch1() external onlyOwner {
// Contract should be powered up
require(contractPoweredUp);
// Bounty batch should not be transferred previously
require(!batch1Transferred);
// Perform transfers
transferParsecs(0x254E9475169B5b1681e0E282476a764CfEe303C9, 38199052000000);
transferParsecs(0xfD854E01dDadAa35F64fC1C491347963B6562D2D, 43127962000000);
transferParsecs(0x9c99eeB6a3CC8aC6Dcf8575575BbCff7a0D87896, 34502370000000);
transferParsecs(0xCBC8Bbf61326422067A17D31a1daF33e8f0B70c8, 11090047000000);
transferParsecs(0x9fEFd6C32E435435921be98D5251A35EB4B9339d, 2843602000000);
transferParsecs(0x2CCE6c9D6a95A8fa8485578119b399b1759e6292, 2843602000000);
transferParsecs(0xC7E98A1f2F749B9737878748DDf971EA3234077d, 7393365000000);
transferParsecs(0x4230D0704cDDd9242A0C98418138Dd068D52c8A1, 6926733000000);
transferParsecs(0xD896714537310f20DB563Ae28E7226e4fBE2ceE2, 10397400000000);
transferParsecs(0x542F72DC468606877877Ce971deCe03C9bEB67d5, 8221483000000);
transferParsecs(0x9BDbEb5F6E59dd471Bc296B97266D3Ee634B7c7e, 8958390000000);
transferParsecs(0x84c10c798ee82D4b8Cf229E40267e6efa9BbF6Dd, 1857480000000);
transferParsecs(0x72a5b7Fc75DC27f9Da2748373b07a883896411f3, 5079250000000);
transferParsecs(0x2DABBC7db7a6bF55B1356AFacBCc882a32301c55, 2171171000000);
transferParsecs(0x11D1e70F657399bAAd0849Edd93a2F52cb5f35F9, 3132236000000);
transferParsecs(0x91AA1bF579cf66847d833925F77e26237fdFcA91, 3216880000000);
transferParsecs(0xC50CD9c617cF4095533578236CFeAE149EFbcE87, 2569505000000);
transferParsecs(0x9E1216e6731D66F22DE9115A6A363aDF76D913CE, 2136292000000);
transferParsecs(0xaaf48F8743C985D3191508C066799Ebed00Dc0d8, 1991888000000);
transferParsecs(0xD3ec5A07125761494B38aE7c67e6D203dD419aae, 1284753000000);
transferParsecs(0x8194A6A9f0B2fE02344FCd7F41DdFAb6539fB52F, 577617000000);
transferParsecs(0x9D3afA524B87Ba0a3b0907d3dF879d4b8F044A73, 1065629000000);
transferParsecs(0xf539d423E2175B7cD82061eff7072C328B309230, 433213000000);
transferParsecs(0xfd052EC542Db2d8d179C97555434C12277a2da90, 4003984000000);
transferParsecs(0xCFe1Bd70Ae72B9c7BC319f94c512D8f96FCcb4C8, 3466135000000);
transferParsecs(0xDdE12A1B5718D002e8AC78216720Eb9BF3C6DBFb, 4541833000000);
transferParsecs(0x31a570a588DC86fAeB45057e749533FB0cD9622d, 358566000000);
transferParsecs(0x9B6286cb7D58c90Ca49B5B6900C5A3B98f5f77cd, 1010585000000);
transferParsecs(0x9BE1c7a1F118F61740f01e96d292c0bae90360aB, 597610000000);
transferParsecs(0x123422Cf323c57DE45361d361e6C8AB3B8391503, 1254980000000);
// Mark bounty batch as transferred
batch1Transferred = true;
}
/// @notice Transfer bounty batch 2 / 3
function ownerTransferBatch2() external onlyOwner {
// Contract should be powered up
require(contractPoweredUp);
// Bounty batch should not be transferred previously
require(!batch2Transferred);
// Perform transfers
transferParsecs(0x3F0CFF7cb4fF4254031BcEf80412e4Cafe4AeC7A, 2185884000000);
transferParsecs(0xD92E4C34093a0091c1DA3fd4f97d90F8cD67a2E9, 1135458000000);
transferParsecs(0x38b324834410f17D236d9f885370289201cF948F, 776892000000);
transferParsecs(0xC38e638025e22A046c7FCe29e56F628906f9d040, 836653000000);
transferParsecs(0x3AA113B6852E60a4C2ba115dfcd4951daeC57c78, 358566000000);
transferParsecs(0x6617503541FD6CF5548820A4FdE7b14211397206, 836653000000);
transferParsecs(0xD97566a98b9bCedC60f8814114AC371e3abA33E8, 358566000000);
transferParsecs(0xc97078d9ecc953a8e263626892da1f17579fa6e6, 12000000000000);
transferParsecs(0x448202bf8a049460bfa60527daca2ff3d47294b4, 7200000000000);
transferParsecs(0x9286d9DeD3Bb4C4CE54e10A8c484e190dA455696, 7200000000000);
transferParsecs(0x1B55887509d4d07965e20842cddaA1B1C4AD559c, 19200000000000);
transferParsecs(0xaC340Cbf45502e509ffC5F213c882516C964202A, 7200000000000);
transferParsecs(0x4638f2cB0CF6d864f351a06d068e4aFb642FAfa2, 7200000000000);
transferParsecs(0x5325D89F64FA6B93C06DB2E6f6d1E672Cffb15fe, 1666667000000);
transferParsecs(0x95D4914d4f08732A169367674A8BE026c02c5B44, 20903813000000);
transferParsecs(0x70580eA14d98a53fd59376dC7e959F4a6129bB9b, 7247431000000);
transferParsecs(0x387c71683A05Cdf4Df2ccd861ad4eeD16F09F917, 10378099000000);
transferParsecs(0xB87e73ad25086C43a16fE5f9589Ff265F8A3A9Eb, 6666667000000);
transferParsecs(0xA443838ad905148232F78F9521577c38932cd832, 5333333000000);
transferParsecs(0x237706bfE11D4C4E148b4764c8f7Da37743657d4, 1161525000000);
transferParsecs(0x28687f8Ae963a33db8fC94C04e231083bd18Af4F, 871143000000);
transferParsecs(0x04f6bf3dc198becdda5fd7bb2cbfd4403b7bd522, 1161525000000);
transferParsecs(0xF4919c366c3ad386f0A5Abe322d6cDe0238CeB28, 1161525000000);
transferParsecs(0xD399E4f178D269DbdaD44948FdEE157Ca574E286, 871143000000);
transferParsecs(0x5889823CD24E11222ba370732218ffE1D9938108, 871143000000);
transferParsecs(0xb906b0641DD9578287c0B7Dbe33aFeC499F1841B, 1451906000000);
transferParsecs(0x1461b1E13ac15B849B8fa54DcFa93B3961992642, 1161525000000);
transferParsecs(0xe415638FC30b277EC7F466E746ABf2d406f821FF, 2177858000000);
transferParsecs(0xde7fb34d93f672a5d587dc0f8a416b13eed8547d, 2323049000000);
transferParsecs(0x76cc93e01a6d810a1c11bbc1054c37cb395f14c8, 3774956000000);
// Mark bounty batch as transferred
batch2Transferred = true;
}
/// @notice Transfer bounty batch 3 / 3
function ownerTransferBatch3() external onlyOwner {
// Contract should be powered up
require(contractPoweredUp);
// Bounty batch should not be transferred previously
require(!batch3Transferred);
// Perform transfers
transferParsecs(0xBE762c447BA88E1B22C5A7248CBEF103032B8306, 871143000000);
transferParsecs(0xED2D17430709eddE66A3E67C2Dd761738fFD0fFd, 1742286000000);
transferParsecs(0x472d1DdfFB017E9EBBB4B6d0d4e1296Af14bD703, 871143000000);
transferParsecs(0xfe4A4DA8DE5565e76392b79615375dDf6C504d11, 3194192000000);
transferParsecs(0xb967dDb883b417f620AaF09505fEBB77Ce0c2374, 1161525000000);
transferParsecs(0xE633a1270A7086e1E4923835C0A5Cf06893D6a01, 871143000000);
transferParsecs(0x1eE06F228451C2d882b7afe6fD737989665BEc52, 1016334000000);
transferParsecs(0x36d091393dcEcd628C52ED4F7B80674107D66Bfa, 871143000000);
transferParsecs(0xb8Bb1F1423f66712Dbc9bC723411397480Acd32f, 871143000000);
transferParsecs(0x42FC0b269713e6F07974191a2c2303dB68d5f681, 871143000000);
transferParsecs(0x8BF0d9afCd2Bd5A779fBFa53b702C7B5A5EEBA05, 1742286000000);
transferParsecs(0x2b9840F282F167E8e8b0Ed8c2938DCaa1006c5D4, 2177858000000);
transferParsecs(0xbdD5645986F492954465b5E407f7528C0cF88fFA, 871143000000);
transferParsecs(0xbB1b7c3DA8920E63B2dc57193a79bbc237AAec7e, 1742286000000);
transferParsecs(0x5c582DE6968264f1865C63DD72f0904bE8e3dA4a, 871143000000);
transferParsecs(0xccb98e6af2b1dbe621fbac6b48e6e98811fe1243, 2613431000000);
transferParsecs(0x4C2C20542d75E08328d21f0c7365823d2752e07c, 1161525000000);
transferParsecs(0x944f0d58ec256528116D622330B93F8Af80c8c35, 1161525000000);
transferParsecs(0x6eB0B9EbC4eD419F5e7330620d647E4113Ae29EF, 4936481000000);
transferParsecs(0x9d13dF46A009e1c6195908043166cf86d885ED84, 1742286000000);
transferParsecs(0x4A116f5605159Db8F958F19e57712EFe3A29F99b, 1742286000000);
transferParsecs(0x4897447ad5b75B30ff3D988628a6AE12b71ED15B, 2032668000000);
transferParsecs(0xb4F9F2bA99b6BE2759ED7461058e80c2297734eA, 2323050000000);
transferParsecs(0xD76fE7347bEB14C9BD0D5A50bf3B69A4e27CFa3b, 1742286000000);
transferParsecs(0x2a06C794A2B2D7F86094765C258f1a1B06CA1813, 1161525000000);
transferParsecs(0x7375C73586881AcC913015E56cccB4c9D63AAf45, 2613429000000);
transferParsecs(0x469579CaC0F8C4e62195b25449B885e5e048D2dC, 2613429000000);
transferParsecs(0x43D58a3D64062e4E2cF6aD285c7FE3a8B25741cC, 3484575000000);
// Mark bounty batch as transferred
batch3Transferred = true;
}
/// @dev Transfer bounty in Parsecs
function transferParsecs(address participant, uint256 value) private {
// Participant's bounty is increased by value
bountyOf[participant] = bountyOf[participant].add(value);
// Increase total transferred bounty
totalTransferredBounty = totalTransferredBounty.add(value);
// Log an event of the participant's bounty
LogCampaignBounty(participant, value, now);
// Transfer Parsecs
parsecToken.transfer(participant, value);
}
} | Transfer bounty in Parsecs Participant's bounty is increased by value Increase total transferred bounty Log an event of the participant's bounty Transfer Parsecs | function transferParsecs(address participant, uint256 value) private {
bountyOf[participant] = bountyOf[participant].add(value);
totalTransferredBounty = totalTransferredBounty.add(value);
LogCampaignBounty(participant, value, now);
parsecToken.transfer(participant, value);
}
| 6,401,024 |
/**
*Submitted for verification at Etherscan.io on 2021-09-20
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
// Part: OpenZeppelin/[email protected]/Address
/**
* @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);
}
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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/[email protected]/Context
/*
* @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;
}
}
// Part: OpenZeppelin/[email protected]/IERC165
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/IERC721Receiver
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/SafeMath
// 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 no longer needed starting with Solidity 0.8. 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;
}
}
}
// Part: OpenZeppelin/[email protected]/Strings
/**
* @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);
}
}
// Part: OpenZeppelin/[email protected]/ERC165
/**
* @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;
}
}
// Part: OpenZeppelin/[email protected]/IERC721
/**
* @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;
}
// Part: OpenZeppelin/[email protected]/Ownable
/**
* @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() {
_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);
}
}
// Part: OpenZeppelin/[email protected]/IERC721Enumerable
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/IERC721Metadata
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/ERC721
/**
* @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 {
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 = 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 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("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 {}
}
// Part: OpenZeppelin/[email protected]/ERC721Enumerable
/**
* @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();
}
}
// Part: OpenZeppelin/[email protected]/ERC721URIStorage
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).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(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @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 override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// File: CryptoBeefcakes.sol
/// @title Smart contract for governing the Crypto Beefcakes ERC721 NFTs
/// @author Crypto Beefcakes
/// @notice This contract is used for minting Crypto Beefcake NFTs
contract CryptoBeefcakes is ERC721URIStorage, ERC721Enumerable, Ownable {
using SafeMath for uint256;
// Metadata base URI
string _metadataBaseURI;
// Sale state
enum SaleState {
NOT_ACTIVE, // 0
WHITELISTED_PRESALE, // 1
OPEN_PRESALE, // 2
PUBLIC_SALE // 3
}
SaleState public saleState = SaleState.NOT_ACTIVE;
// Presale tokens minted
uint256 public presaleTokensMinted = 0;
// Presale whitelist
mapping(address => bool) public presaleWhitelisted;
// Discounted referral mints
mapping(address => uint) public addressToNumReferralMints;
// Minting constants
uint256 public constant MAX_BEEFCAKES = 9999; // 9999 beefcake limit
uint256 public constant MAX_BEEFCAKE_PURCHASE = 20; // 20 beefcake purchase (mint) limit per transaction
uint256 public constant BEEFCAKE_EARLY_PRICE = 4 ether / 100; // 0.04 ETH early price
uint256 public constant BEEFCAKE_PRICE = 6 ether / 100; // 0.06 ETH price
uint256 public constant REFERRAL_DISCOUNT = 1 ether / 100; // 0.01 ETH referral discount t REFERRAL_DISCOUNT = 1 ether / 100; // 0.01 ETH referral discount
uint256 public constant MAX_PRESALE_TOKENS = 500; // 500 maximum tokens can be minted for presale
// Minted event
event BeefcakeMinted(uint256 tokenId); // Event to monitor
// Default constructor
constructor() ERC721("Crypto Beefcakes", "BEEF") Ownable() {}
// Withdraw funds
function withdraw() public onlyOwner {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
// Sale state changes
function startGeneralSale() public onlyOwner {
saleState = SaleState.PUBLIC_SALE;
}
function startWhitelistedPresale() public onlyOwner {
saleState = SaleState.WHITELISTED_PRESALE;
}
function startOpenPresale() public onlyOwner {
saleState = SaleState.OPEN_PRESALE;
}
function stopSale() public onlyOwner {
saleState = SaleState.NOT_ACTIVE;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_metadataBaseURI = baseURI;
}
function _baseURI() override(ERC721) view internal returns (string memory) {
return _metadataBaseURI;
}
// Set token URI for metadata
function setTokenURI(uint256 tokenId, string memory _tokenURI) public onlyOwner {
_setTokenURI(tokenId, _tokenURI);
}
/// @notice Get the price of minting a Beefcake NFT for a given address, based on general sale or presale status and referral discount
/// @param minterAddress The address for the minter
/// @return The price in wei
function getPrice(address minterAddress) public view returns(uint256) {
// Get price based on presale status
uint price = (saleState == SaleState.WHITELISTED_PRESALE || saleState == SaleState.OPEN_PRESALE)? BEEFCAKE_EARLY_PRICE : BEEFCAKE_PRICE;
// Add referral discount
if(addressToNumReferralMints[minterAddress] > 0) {
return price.sub(REFERRAL_DISCOUNT);
} else {
return price;
}
}
// Reserve Beefcakes for giveaways and airdrops
function reserveBeefcakes() public onlyOwner {
uint256 numBeefcakes = 30;
require(totalSupply().add(numBeefcakes) <= MAX_BEEFCAKES, "Error: all beefcakes have already been minted");
// Mint these beefcakes
for(uint i =0; i < numBeefcakes; i++) {
uint256 tokenId = totalSupply();
_safeMint(msg.sender, tokenId);
emit BeefcakeMinted(tokenId);
}
}
/// @notice Determine if user can mint based on the sale's state
/// @param minterAddress The address of the would-be minter
/// @return A bool indicating whether or not the would-b minter can mint
function canMint(address minterAddress) public view returns(bool) {
// Can mint if public sale or open presale
if(saleState == SaleState.PUBLIC_SALE || saleState == SaleState.OPEN_PRESALE) {
return true;
}
// Can mint if whitelisted presale is ongoing and the minter is whitelisted
if(saleState == SaleState.WHITELISTED_PRESALE && presaleWhitelisted[minterAddress]) {
return true;
}
return false;
}
/// @notice Mint Beefcake tokens, up to 20 tokens at a time
/// @param numBeefcakes The number of Beefcakes you want to mint, with 20 being the max value
function mint(uint256 numBeefcakes) payable public {
require(canMint(msg.sender), "Error: you are not allowed to mint at this time");
require(numBeefcakes <= MAX_BEEFCAKE_PURCHASE, "Error: can only mint 20 beefcakes per transaction");
uint256 price = getPrice(msg.sender);
require(msg.value >= price.mul(numBeefcakes), "Error: insufficient funds sent");
require(totalSupply().add(numBeefcakes) <= MAX_BEEFCAKES, "Error: all beefcakes have already been minted");
if(saleState == SaleState.WHITELISTED_PRESALE || saleState == SaleState.OPEN_PRESALE) {
require(presaleTokensMinted.add(numBeefcakes) <= MAX_PRESALE_TOKENS, "Error: only 500 presale tokens can be minted TOTAL");
}
// Reduce number of referall mints
if(addressToNumReferralMints[msg.sender] > 0) {
addressToNumReferralMints[msg.sender] = addressToNumReferralMints[msg.sender].sub(1);
}
// Increase number of presale mints
if(saleState == SaleState.WHITELISTED_PRESALE || saleState == SaleState.OPEN_PRESALE) {
presaleTokensMinted = presaleTokensMinted.add(numBeefcakes);
}
// Mint these beefcakes
for(uint i = 0; i < numBeefcakes; i++) {
uint256 tokenId = totalSupply();
_safeMint(msg.sender, tokenId);
emit BeefcakeMinted(tokenId);
}
}
/// @notice Mint with referral -- when you mint with a referral, your referrer will receive a discount on their next Beefcake mint
/// @param numBeefcakes The number of Beefcakes you want to mint, with 20 being the max value
/// @param referrerAddress The address of the referrer -- this referrer must have previously minted a Beefcake
function mintWithReferral(uint256 numBeefcakes, address referrerAddress) payable public {
require(balanceOf(referrerAddress) > 0, "Error: referrer must have minted already");
require(referrerAddress != msg.sender, "Error: cannot refer yourself");
addressToNumReferralMints[referrerAddress] = addressToNumReferralMints[referrerAddress].add(1);
mint(numBeefcakes);
}
// Whitelist accounts for presale
function whitelistForPresale(address[] memory presaleAddresses) public onlyOwner {
for(uint i =0; i < presaleAddresses.length; i++) {
presaleWhitelisted[presaleAddresses[i]] = true;
}
}
// The following functions are overrides required by Solidity.
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721URIStorage, ERC721)
returns (string memory)
{
return ERC721URIStorage.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
} | Whitelist accounts for presale | function whitelistForPresale(address[] memory presaleAddresses) public onlyOwner {
for(uint i =0; i < presaleAddresses.length; i++) {
presaleWhitelisted[presaleAddresses[i]] = true;
}
}
| 1,992,198 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
import "./external/@openzeppelin/token/ERC20/extensions/IERC20Metadata.sol";
import "./external/spool-core/SpoolOwnable.sol";
import "./interfaces/IVoSPOOL.sol";
/* ========== STRUCTS ========== */
/**
* @notice global tranche struct
* @dev used so it can be passed through functions as a struct
* @member amount amount minted in tranche
*/
struct Tranche {
uint48 amount;
}
/**
* @notice global tranches struct holding 5 tranches
* @dev made to pack multiple tranches in one word
* @member zero tranche in pack at position 0
* @member one tranche in pack at position 1
* @member two tranche in pack at position 2
* @member three tranche in pack at position 3
* @member four tranche in pack at position 4
*/
struct GlobalTranches {
Tranche zero;
Tranche one;
Tranche two;
Tranche three;
Tranche four;
}
/**
* @notice user tranche struct
* @dev struct holds users minted amount at tranche at index
* @member amount users amount minted at tranche
* @member index tranche index
*/
struct UserTranche {
uint48 amount;
uint16 index;
}
/**
* @notice user tranches struct, holding 4 user tranches
* @dev made to pack multiple tranches in one word
* @member zero user tranche in pack at position 0
* @member one user tranche in pack at position 1
* @member two user tranche in pack at position 2
* @member three user tranche in pack at position 3
*/
struct UserTranches {
UserTranche zero;
UserTranche one;
UserTranche two;
UserTranche three;
}
/**
* @title Spool DAO Voting Token Implementation
*
* @notice The voting SPOOL pseudo-ERC20 Implementation
*
* An untransferable token implementation meant to be used by the
* Spool DAO to mint the voting equivalent of the staked token.
*
* @dev
* Users voting power consists of instant and gradual (maturing) voting power.
* voSPOOL contract assumes voting power comes from vesting or staking SPOOL tokens.
* As SPOOL tokens have a maximum supply of 210,000,000 * 10**18, we consider this
* limitation when storing data (e.g. storing amount divided by 10**12) to save on gas.
*
* Instant voting power can be used in the full amount as soon as minted.
*
* Gradual voting power:
* Matures linearly over 156 weeks (3 years) up to the minted amount.
* If a user burns gradual voting power, all accumulated voting power is
* reset to zero. In case there is some amount left, it'll take another 3
* years to achieve fully-matured power. Only gradual voting power is reset
* and not instant one.
* Gradual voting power updates at every new tranche, which lasts one week.
*
* Contract consists of:
* - CONSTANTS
* - STATE VARIABLES
* - CONSTRUCTOR
* - IERC20 FUNCTIONS
* - INSTANT POWER FUNCTIONS
* - GRADUAL POWER FUNCTIONS
* - GRADUAL POWER: VIEW FUNCTIONS
* - GRADUAL POWER: MINT FUNCTIONS
* - GRADUAL POWER: BURN FUNCTIONS
* - GRADUAL POWER: UPDATE GLOBAL FUNCTIONS
* - GRADUAL POWER: UPDATE USER FUNCTIONS
* - GRADUAL POWER: GLOBAL HELPER FUNCTIONS
* - GRADUAL POWER: USER HELPER FUNCTIONS
* - GRADUAL POWER: HELPER FUNCTIONS
* - OWNER FUNCTIONS
* - RESTRICTION FUNCTIONS
* - MODIFIERS
*/
contract VoSPOOL is SpoolOwnable, IVoSPOOL, IERC20Metadata {
/* ========== CONSTANTS ========== */
/// @notice trim size value of the mint amount
/// @dev we trim gradual mint amount by `TRIM_SIZE`, so it takes less storage
uint256 private constant TRIM_SIZE = 10**12;
/// @notice number of tranche amounts stored in one 256bit word
uint256 private constant TRANCHES_PER_WORD = 5;
/// @notice duration of one tranche
uint256 public constant TRANCHE_TIME = 1 weeks;
/// @notice amount of tranches to mature to full power
uint256 public constant FULL_POWER_TRANCHES_COUNT = 52 * 3;
/// @notice time until gradual power is fully-matured
/// @dev full power time is 156 weeks (approximately 3 years)
uint256 public constant FULL_POWER_TIME = TRANCHE_TIME * FULL_POWER_TRANCHES_COUNT;
/// @notice Token name full name
string public constant name = "Spool DAO Voting Token";
/// @notice Token symbol
string public constant symbol = "voSPOOL";
/// @notice Token decimals
uint8 public constant decimals = 18;
/* ========== STATE VARIABLES ========== */
/// @notice tranche time for index 1
uint256 public immutable firstTrancheStartTime;
/// @notice mapping holding instant minting privileges for addresses
mapping(address => bool) public minters;
/// @notice mapping holding gradual minting privileges for addresses
mapping(address => bool) public gradualMinters;
/// @notice total instant voting power
uint256 public totalInstantPower;
/// @notice user instant voting power
mapping(address => uint256) public userInstantPower;
/// @notice global gradual power values
GlobalGradual private _globalGradual;
/// @notice global tranches
/// @dev mapping tranche index to a group of tranches (5 tranches per word)
mapping(uint256 => GlobalTranches) public indexedGlobalTranches;
/// @notice user gradual power values
mapping(address => UserGradual) private _userGraduals;
/// @notice user tranches
/// @dev mapping users to its tranches
mapping(address => mapping(uint256 => UserTranches)) public userTranches;
/* ========== CONSTRUCTOR ========== */
/**
* @notice Sets the value of _spoolOwner and first tranche end time
* @dev With `_firstTrancheEndTime` you can set when the first tranche time
* finishes and essentially users minted get the first foting power.
* e.g. if we set it to Sunday 10pm and tranche time is 1 week,
* all new tranches in the future will finish on Sunday 10pm and new
* voSPOOL power will mature and be accrued.
*
* Requirements:
*
* - first tranche time must be in the future
* - first tranche time must must be less than full tranche time in the future
*
* @param _spoolOwner address of spool owner contract
* @param _firstTrancheEndTime first tranche end time after the deployment
*/
constructor(ISpoolOwner _spoolOwner, uint256 _firstTrancheEndTime) SpoolOwnable(_spoolOwner) {
require(
_firstTrancheEndTime > block.timestamp,
"voSPOOL::constructor: First tranche end time must be in the future"
);
require(
_firstTrancheEndTime < block.timestamp + TRANCHE_TIME,
"voSPOOL::constructor: First tranche end time must be less than full tranche time in the future"
);
unchecked {
// set first tranche start time
firstTrancheStartTime = _firstTrancheEndTime - TRANCHE_TIME;
}
}
/* ========== IERC20 FUNCTIONS ========== */
/**
* @notice Returns current total voting power
*/
function totalSupply() external view override returns (uint256) {
(GlobalGradual memory global, ) = _getUpdatedGradual();
return totalInstantPower + _getTotalGradualVotingPower(global);
}
/**
* @notice Returns current user total voting power
*/
function balanceOf(address account) external view override returns (uint256) {
(UserGradual memory _userGradual, ) = _getUpdatedGradualUser(account);
return userInstantPower[account] + _getUserGradualVotingPower(_userGradual);
}
/**
* @dev Execution of function is prohibited to disallow token movement
*/
function transfer(address, uint256) external pure override returns (bool) {
revert("voSPOOL::transfer: Prohibited Action");
}
/**
* @dev Execution of function is prohibited to disallow token movement
*/
function transferFrom(
address,
address,
uint256
) external pure override returns (bool) {
revert("voSPOOL::transferFrom: Prohibited Action");
}
/**
* @dev Execution of function is prohibited to disallow token movement
*/
function approve(address, uint256) external pure override returns (bool) {
revert("voSPOOL::approve: Prohibited Action");
}
/**
* @dev Execution of function is prohibited to disallow token movement
*/
function allowance(address, address) external pure override returns (uint256) {
revert("voSPOOL::allowance: Prohibited Action");
}
/* ========== INSTANT POWER FUNCTIONS ========== */
/**
* @notice Mints the provided amount as instant voting power.
*
* Requirements:
*
* - the caller must be the autorized
*
* @param to mint to user
* @param amount mint amount
*/
function mint(address to, uint256 amount) external onlyMinter {
totalInstantPower += amount;
unchecked {
userInstantPower[to] += amount;
}
emit Minted(to, amount);
}
/**
* @notice Burns the provided amount of instant power from the specified user.
* @dev only instant power is removed, gradual power stays the same
*
* Requirements:
*
* - the caller must be the instant minter
* - the user must posses at least the burning `amount` of instant voting power amount
*
* @param from burn from user
* @param amount burn amount
*/
function burn(address from, uint256 amount) external onlyMinter {
require(userInstantPower[from] >= amount, "voSPOOL:burn: User instant power balance too low");
unchecked {
userInstantPower[from] -= amount;
totalInstantPower -= amount;
}
emit Burned(from, amount);
}
/* ========== GRADUAL POWER FUNCTIONS ========== */
/* ---------- GRADUAL POWER: VIEW FUNCTIONS ---------- */
/**
* @notice returns updated total gradual voting power (fully-matured and maturing)
*
* @return totalGradualVotingPower total gradual voting power (fully-matured + maturing)
*/
function getTotalGradualVotingPower() external view returns (uint256) {
(GlobalGradual memory global, ) = _getUpdatedGradual();
return _getTotalGradualVotingPower(global);
}
/**
* @notice returns updated global gradual struct
*
* @return global updated global gradual struct
*/
function getGlobalGradual() external view returns (GlobalGradual memory) {
(GlobalGradual memory global, ) = _getUpdatedGradual();
return global;
}
/**
* @notice returns not updated global gradual struct
*
* @return global updated global gradual struct
*/
function getNotUpdatedGlobalGradual() external view returns (GlobalGradual memory) {
return _globalGradual;
}
/**
* @notice returns updated user gradual voting power (fully-matured and maturing)
*
* @param user address holding voting power
* @return userGradualVotingPower user gradual voting power (fully-matured + maturing)
*/
function getUserGradualVotingPower(address user) external view returns (uint256) {
(UserGradual memory _userGradual, ) = _getUpdatedGradualUser(user);
return _getUserGradualVotingPower(_userGradual);
}
/**
* @notice returns updated user gradual struct
*
* @param user user address
* @return _userGradual user updated gradual struct
*/
function getUserGradual(address user) external view returns (UserGradual memory) {
(UserGradual memory _userGradual, ) = _getUpdatedGradualUser(user);
return _userGradual;
}
/**
* @notice returns not updated user gradual struct
*
* @param user user address
* @return _userGradual user updated gradual struct
*/
function getNotUpdatedUserGradual(address user) external view returns (UserGradual memory) {
return _userGraduals[user];
}
/**
* @notice Returns current active tranche index
*
* @return trancheIndex current tranche index
*/
function getCurrentTrancheIndex() public view returns (uint16) {
return _getTrancheIndex(block.timestamp);
}
/**
* @notice Returns tranche index based on `time`
* @dev `time` can be any time inside the tranche
*
* Requirements:
*
* - `time` must be equal to more than first tranche time
*
* @param time tranche time time to get the index for
* @return trancheIndex tranche index at `time`
*/
function getTrancheIndex(uint256 time) external view returns (uint256) {
require(
time >= firstTrancheStartTime,
"voSPOOL::getTrancheIndex: Time must be more or equal to the first tranche time"
);
return _getTrancheIndex(time);
}
/**
* @notice Returns tranche index based at time
*
* @param time unix time
* @return trancheIndex tranche index at `time`
*/
function _getTrancheIndex(uint256 time) private view returns (uint16) {
unchecked {
return uint16(((time - firstTrancheStartTime) / TRANCHE_TIME) + 1);
}
}
/**
* @notice Returns next tranche end time
*
* @return trancheEndTime end time for next tranche
*/
function getNextTrancheEndTime() external view returns (uint256) {
return getTrancheEndTime(getCurrentTrancheIndex());
}
/**
* @notice Returns tranche end time for tranche index
*
* @param trancheIndex tranche index
* @return trancheEndTime end time for `trancheIndex`
*/
function getTrancheEndTime(uint256 trancheIndex) public view returns (uint256) {
return firstTrancheStartTime + trancheIndex * TRANCHE_TIME;
}
/**
* @notice Returns last finished tranche index
*
* @return trancheIndex last finished tranche index
*/
function getLastFinishedTrancheIndex() public view returns (uint16) {
unchecked {
return getCurrentTrancheIndex() - 1;
}
}
/* ---------- GRADUAL POWER: MINT FUNCTIONS ---------- */
/**
* @notice Mints the provided amount of tokens to the specified user to gradually mature up to the amount.
* @dev Saves the amount to tranche user index, so the voting power starts maturing.
*
* Requirements:
*
* - the caller must be the autorized
*
* @param to gradual mint to user
* @param amount gradual mint amount
*/
function mintGradual(address to, uint256 amount) external onlyGradualMinter updateGradual updateGradualUser(to) {
uint48 trimmedAmount = _trim(amount);
_mintGradual(to, trimmedAmount);
emit GradualMinted(to, amount);
}
/**
* @notice Mints the provided amount of tokens to the specified user to gradually mature up to the amount.
* @dev Saves the amount to tranche user index, so the voting power starts maturing.
*
* @param to gradual mint to user
* @param trimmedAmount gradual mint trimmed amount
*/
function _mintGradual(address to, uint48 trimmedAmount) private {
if (trimmedAmount == 0) {
return;
}
UserGradual memory _userGradual = _userGraduals[to];
// add new maturing amount to user and global amount
_userGradual.maturingAmount += trimmedAmount;
_globalGradual.totalMaturingAmount += trimmedAmount;
// add maturing amount to user tranche
UserTranche memory latestTranche = _getUserTranche(to, _userGradual.latestTranchePosition);
uint16 currentTrancheIndex = getCurrentTrancheIndex();
bool isFirstGradualMint = !_hasTranches(_userGradual);
// if latest user tranche is not current index, update latest
// user can have first mint or last tranche deposited is finished
if (isFirstGradualMint || latestTranche.index < currentTrancheIndex) {
UserTranchePosition memory nextTranchePosition = _getNextUserTranchePosition(
_userGradual.latestTranchePosition
);
// if first time gradual minting set oldest tranche position
if (isFirstGradualMint) {
_userGradual.oldestTranchePosition = nextTranchePosition;
}
// update latest tranche
_userGradual.latestTranchePosition = nextTranchePosition;
latestTranche = UserTranche(trimmedAmount, currentTrancheIndex);
} else {
// if user already minted in current tranche, add additional amount
latestTranche.amount += trimmedAmount;
}
// update global tranche amount
_addGlobalTranche(latestTranche.index, trimmedAmount);
// store updated user values
_setUserTranche(to, _userGradual.latestTranchePosition, latestTranche);
_userGraduals[to] = _userGradual;
}
/**
* @notice add `amount` to global tranche `index`
*
* @param index tranche index
* @param amount amount to add
*/
function _addGlobalTranche(uint256 index, uint48 amount) private {
Tranche storage tranche = _getTranche(index);
tranche.amount += amount;
}
/**
* @notice sets updated `user` `tranche` at position
*
* @param user user address to set tranche
* @param userTranchePosition position to set the `tranche` at
* @param tranche updated `user` tranche
*/
function _setUserTranche(
address user,
UserTranchePosition memory userTranchePosition,
UserTranche memory tranche
) private {
UserTranches storage _userTranches = userTranches[user][userTranchePosition.arrayIndex];
if (userTranchePosition.position == 0) {
_userTranches.zero = tranche;
} else if (userTranchePosition.position == 1) {
_userTranches.one = tranche;
} else if (userTranchePosition.position == 2) {
_userTranches.two = tranche;
} else {
_userTranches.three = tranche;
}
}
/* ---------- GRADUAL POWER: BURN FUNCTIONS ---------- */
/**
* @notice Burns the provided amount of gradual power from the specified user.
* @dev User loses all matured power accumulated till now.
* Voting power starts maturing from the start if there is any amount left.
*
* Requirements:
*
* - the caller must be the gradual minter
*
* @param from burn from user
* @param amount burn amount
* @param burnAll true to burn all user amount
*/
function burnGradual(
address from,
uint256 amount,
bool burnAll
) external onlyGradualMinter updateGradual updateGradualUser(from) {
UserGradual memory _userGradual = _userGraduals[from];
uint48 userTotalGradualAmount = _userGradual.maturedVotingPower + _userGradual.maturingAmount;
// remove user matured power
if (_userGradual.maturedVotingPower > 0) {
_globalGradual.totalMaturedVotingPower -= _userGradual.maturedVotingPower;
_userGradual.maturedVotingPower = 0;
}
// remove user maturing
if (_userGradual.maturingAmount > 0) {
_globalGradual.totalMaturingAmount -= _userGradual.maturingAmount;
_userGradual.maturingAmount = 0;
}
// remove user unmatured power
if (_userGradual.rawUnmaturedVotingPower > 0) {
_globalGradual.totalRawUnmaturedVotingPower -= _userGradual.rawUnmaturedVotingPower;
_userGradual.rawUnmaturedVotingPower = 0;
}
// if user has any tranches, remove all of them from user and global
if (_hasTranches(_userGradual)) {
uint256 fromIndex = _userGradual.oldestTranchePosition.arrayIndex;
uint256 toIndex = _userGradual.latestTranchePosition.arrayIndex;
// loop over user tranches and delete all of them
for (uint256 i = fromIndex; i <= toIndex; i++) {
// delete from global tranches
_deleteUserTranchesFromGlobal(userTranches[from][i]);
// delete user tranches
delete userTranches[from][i];
}
}
// reset oldest tranche (meaning user has no tranches)
_userGradual.oldestTranchePosition = UserTranchePosition(0, 0);
// apply changes to storage
_userGraduals[from] = _userGradual;
emit GradualBurned(from, amount, burnAll);
// if we don't burn all gradual amount, restart maturing
if (!burnAll) {
uint48 trimmedAmount = _trimRoundUp(amount);
// if user still has some amount left, mint gradual from start
if (userTotalGradualAmount > trimmedAmount) {
unchecked {
uint48 userAmountLeft = userTotalGradualAmount - trimmedAmount;
// mint amount left
_mintGradual(from, userAmountLeft);
}
}
}
}
/**
* @notice remove user tranches amounts from global tranches
* @dev remove for all four user tranches in the struct
*
* @param _userTranches user tranches
*/
function _deleteUserTranchesFromGlobal(UserTranches memory _userTranches) private {
_removeUserTrancheFromGlobal(_userTranches.zero);
_removeUserTrancheFromGlobal(_userTranches.one);
_removeUserTrancheFromGlobal(_userTranches.two);
_removeUserTrancheFromGlobal(_userTranches.three);
}
/**
* @notice remove user tranche amount from global tranche
*
* @param userTranche user tranche
*/
function _removeUserTrancheFromGlobal(UserTranche memory userTranche) private {
if (userTranche.amount > 0) {
Tranche storage tranche = _getTranche(userTranche.index);
tranche.amount -= userTranche.amount;
}
}
/* ---------- GRADUAL POWER: UPDATE GLOBAL FUNCTIONS ---------- */
/**
* @notice updates global gradual voting power
* @dev
*
* Requirements:
*
* - the caller must be the gradual minter
*/
function updateVotingPower() external override onlyGradualMinter {
_updateGradual();
}
/**
* @notice updates global gradual voting power
* @dev updates only if changes occured
*/
function _updateGradual() private {
(GlobalGradual memory global, bool didUpdate) = _getUpdatedGradual();
if (didUpdate) {
_globalGradual = global;
emit GlobalGradualUpdated(
global.lastUpdatedTrancheIndex,
global.totalMaturedVotingPower,
global.totalMaturingAmount,
global.totalRawUnmaturedVotingPower
);
}
}
/**
* @notice returns updated global gradual values
* @dev the update is in-memory
*
* @return global updated GlobalGradual struct
* @return didUpdate flag if `global` was updated
*/
function _getUpdatedGradual() private view returns (GlobalGradual memory global, bool didUpdate) {
uint256 lastFinishedTrancheIndex = getLastFinishedTrancheIndex();
global = _globalGradual;
// update gradual until we reach last finished index
while (global.lastUpdatedTrancheIndex < lastFinishedTrancheIndex) {
// increment index before updating so we calculate based on finished index
global.lastUpdatedTrancheIndex++;
_updateGradualForTrancheIndex(global);
didUpdate = true;
}
}
/**
* @notice update global gradual values for tranche `index`
* @dev the update is done in-memory on `global` struct
*
* @param global global gradual struct
*/
function _updateGradualForTrancheIndex(GlobalGradual memory global) private view {
// update unmatured voting power
// every new tranche we add totalMaturingAmount to the _totalRawUnmaturedVotingPower
global.totalRawUnmaturedVotingPower += global.totalMaturingAmount;
// move newly matured voting power to matured
// do only if contract is old enough so full power could be achieved
if (global.lastUpdatedTrancheIndex >= FULL_POWER_TRANCHES_COUNT) {
uint256 maturedIndex = global.lastUpdatedTrancheIndex - FULL_POWER_TRANCHES_COUNT + 1;
uint48 newMaturedVotingPower = _getTranche(maturedIndex).amount;
// if there is any new fully-matured voting power, update
if (newMaturedVotingPower > 0) {
// remove new fully matured voting power from non matured raw one
uint56 newMaturedAsRawUnmatured = _getMaturedAsRawUnmaturedAmount(newMaturedVotingPower);
global.totalRawUnmaturedVotingPower -= newMaturedAsRawUnmatured;
// remove new fully-matured power from maturing amount
global.totalMaturingAmount -= newMaturedVotingPower;
// add new fully-matured voting power
global.totalMaturedVotingPower += newMaturedVotingPower;
}
}
}
/* ---------- GRADUAL POWER: UPDATE USER FUNCTIONS ---------- */
/**
* @notice update gradual user voting power
* @dev also updates global gradual voting power
*
* Requirements:
*
* - the caller must be the gradual minter
*
* @param user user address to update
*/
function updateUserVotingPower(address user) external override onlyGradualMinter {
_updateGradual();
_updateGradualUser(user);
}
/**
* @notice update gradual user struct storage
*
* @param user user address to update
*/
function _updateGradualUser(address user) private {
(UserGradual memory _userGradual, bool didUpdate) = _getUpdatedGradualUser(user);
if (didUpdate) {
_userGraduals[user] = _userGradual;
emit UserGradualUpdated(
user,
_userGradual.lastUpdatedTrancheIndex,
_userGradual.maturedVotingPower,
_userGradual.maturingAmount,
_userGradual.rawUnmaturedVotingPower
);
}
}
/**
* @notice returns updated user gradual struct
* @dev the update is returned in-memory
* The update is done in 3 steps:
* 1. check if user ia alreas, update last updated undex
* 2. update voting power for tranches that have fully-matured (if any)
* 3. update voting power for tranches that are still maturing
*
* @param user updated for user address
* @return _userGradual updated user gradual struct
* @return didUpdate flag if user gradual has updated
*/
function _getUpdatedGradualUser(address user) private view returns (UserGradual memory, bool) {
UserGradual memory _userGradual = _userGraduals[user];
uint16 lastFinishedTrancheIndex = getLastFinishedTrancheIndex();
// 1. if user already updated in this tranche index, skip
if (_userGradual.lastUpdatedTrancheIndex == lastFinishedTrancheIndex) {
return (_userGradual, false);
}
// update user if it has maturing power
if (_hasTranches(_userGradual)) {
// 2. update fully-matured tranches
uint16 lastMaturedIndex = _getLastMaturedIndex();
if (lastMaturedIndex > 0) {
UserTranche memory oldestTranche = _getUserTranche(user, _userGradual.oldestTranchePosition);
// update all fully-matured user tranches
while (_hasTranches(_userGradual) && oldestTranche.index <= lastMaturedIndex) {
// mature
_matureOldestUsersTranche(_userGradual, oldestTranche);
// get new user oldest tranche
oldestTranche = _getUserTranche(user, _userGradual.oldestTranchePosition);
}
}
// 3. update still maturing tranches
if (_isMaturing(_userGradual, lastFinishedTrancheIndex)) {
// get number of passed indexes
uint56 indexesPassed = lastFinishedTrancheIndex - _userGradual.lastUpdatedTrancheIndex;
// add new user matured power
_userGradual.rawUnmaturedVotingPower += _userGradual.maturingAmount * indexesPassed;
// last synced index
_userGradual.lastUpdatedTrancheIndex = lastFinishedTrancheIndex;
}
}
// update user last updated tranche index
_userGradual.lastUpdatedTrancheIndex = lastFinishedTrancheIndex;
return (_userGradual, true);
}
/**
* @notice mature users oldest tranche, and update oldest with next user tranche
* @dev this is called only if we know `oldestTranche` is mature
* Updates are done im-memory
*
* @param _userGradual user gradual struct to update
* @param oldestTranche users oldest struct (fully matured one)
*/
function _matureOldestUsersTranche(UserGradual memory _userGradual, UserTranche memory oldestTranche) private pure {
uint16 fullyMaturedFinishedIndex = _getFullyMaturedAtFinishedIndex(oldestTranche.index);
uint48 newMaturedVotingPower = oldestTranche.amount;
// add new matured voting power
// calculate number of passed indexes between last update until fully matured index
uint56 indexesPassed = fullyMaturedFinishedIndex - _userGradual.lastUpdatedTrancheIndex;
_userGradual.rawUnmaturedVotingPower += _userGradual.maturingAmount * indexesPassed;
// update new fully-matured voting power
uint56 newMaturedAsRawUnmatured = _getMaturedAsRawUnmaturedAmount(newMaturedVotingPower);
// update user gradual values in respect of new fully-matured amount
// remove new fully matured voting power from non matured raw one
_userGradual.rawUnmaturedVotingPower -= newMaturedAsRawUnmatured;
// add new fully-matured voting power
_userGradual.maturedVotingPower += newMaturedVotingPower;
// remove new fully-matured power from maturing amount
_userGradual.maturingAmount -= newMaturedVotingPower;
// add next tranche as oldest
_setNextOldestUserTranchePosition(_userGradual);
// update last updated index until fully matured index
_userGradual.lastUpdatedTrancheIndex = fullyMaturedFinishedIndex;
}
/**
* @notice returns index at which the maturing will finish
* @dev
* e.g. if FULL_POWER_TRANCHES_COUNT=2 and passing index=1,
* maturing will complete at the end of index 2.
* This is the index we return, similar to last finished index.
*
* @param index index from which to derive fully matured finished index
*/
function _getFullyMaturedAtFinishedIndex(uint256 index) private pure returns (uint16) {
return uint16(index + FULL_POWER_TRANCHES_COUNT - 1);
}
/**
* @notice updates user oldest tranche position to next one in memory
* @dev this is done after an oldest tranche position matures
* If oldest tranch position is same as latest one, all user
* tranches have matured. In this case we remove tranhe positions from the user
*
* @param _userGradual user gradual struct to update
*/
function _setNextOldestUserTranchePosition(UserGradual memory _userGradual) private pure {
// if oldest tranche is same as latest, this was the last tranche and we remove it from the user
if (
_userGradual.oldestTranchePosition.arrayIndex == _userGradual.latestTranchePosition.arrayIndex &&
_userGradual.oldestTranchePosition.position == _userGradual.latestTranchePosition.position
) {
// reset user tranches as all of them matured
_userGradual.oldestTranchePosition = UserTranchePosition(0, 0);
} else {
// set next user tranche as oldest
_userGradual.oldestTranchePosition = _getNextUserTranchePosition(_userGradual.oldestTranchePosition);
}
}
/* ---------- GRADUAL POWER: GLOBAL HELPER FUNCTIONS ---------- */
/**
* @notice returns total gradual voting power from `global`
* @dev the returned amount is untrimmed
*
* @param global global gradual struct
* @return totalGradualVotingPower total gradual voting power (fully-matured + maturing)
*/
function _getTotalGradualVotingPower(GlobalGradual memory global) private pure returns (uint256) {
return
_untrim(global.totalMaturedVotingPower) +
_getMaturingVotingPowerFromRaw(_untrim(global.totalRawUnmaturedVotingPower));
}
/**
* @notice returns global tranche storage struct
* @dev we return struct, so we can manipulate the storage in other functions
*
* @param index tranche index
* @return tranche tranche storage struct
*/
function _getTranche(uint256 index) private view returns (Tranche storage) {
uint256 arrayindex = index / TRANCHES_PER_WORD;
GlobalTranches storage globalTranches = indexedGlobalTranches[arrayindex];
uint256 globalTranchesPosition = index % TRANCHES_PER_WORD;
if (globalTranchesPosition == 0) {
return globalTranches.zero;
} else if (globalTranchesPosition == 1) {
return globalTranches.one;
} else if (globalTranchesPosition == 2) {
return globalTranches.two;
} else if (globalTranchesPosition == 3) {
return globalTranches.three;
} else {
return globalTranches.four;
}
}
/* ---------- GRADUAL POWER: USER HELPER FUNCTIONS ---------- */
/**
* @notice gets `user` `tranche` at position
*
* @param user user address to get tranche from
* @param userTranchePosition position to get the `tranche` from
* @return tranche `user` tranche
*/
function _getUserTranche(address user, UserTranchePosition memory userTranchePosition)
private
view
returns (UserTranche memory tranche)
{
UserTranches storage _userTranches = userTranches[user][userTranchePosition.arrayIndex];
if (userTranchePosition.position == 0) {
tranche = _userTranches.zero;
} else if (userTranchePosition.position == 1) {
tranche = _userTranches.one;
} else if (userTranchePosition.position == 2) {
tranche = _userTranches.two;
} else {
tranche = _userTranches.three;
}
}
/**
* @notice return last matured tranche index
*
* @return lastMaturedIndex last matured tranche index
*/
function _getLastMaturedIndex() private view returns (uint16 lastMaturedIndex) {
uint256 currentTrancheIndex = getCurrentTrancheIndex();
if (currentTrancheIndex > FULL_POWER_TRANCHES_COUNT) {
unchecked {
lastMaturedIndex = uint16(currentTrancheIndex - FULL_POWER_TRANCHES_COUNT);
}
}
}
/**
* @notice returns the user gradual voting power (fully-matured and maturing)
* @dev the returned amount is untrimmed
*
* @param _userGradual user gradual struct
* @return userGradualVotingPower user gradual voting power (fully-matured + maturing)
*/
function _getUserGradualVotingPower(UserGradual memory _userGradual) private pure returns (uint256) {
return
_untrim(_userGradual.maturedVotingPower) +
_getMaturingVotingPowerFromRaw(_untrim(_userGradual.rawUnmaturedVotingPower));
}
/**
* @notice returns next user tranche position, based on current one
*
* @param currentTranchePosition current user tranche position
* @return nextTranchePosition next tranche position of `currentTranchePosition`
*/
function _getNextUserTranchePosition(UserTranchePosition memory currentTranchePosition)
private
pure
returns (UserTranchePosition memory nextTranchePosition)
{
if (currentTranchePosition.arrayIndex == 0) {
nextTranchePosition.arrayIndex = 1;
} else {
if (currentTranchePosition.position < 3) {
nextTranchePosition.arrayIndex = currentTranchePosition.arrayIndex;
nextTranchePosition.position = currentTranchePosition.position + 1;
} else {
nextTranchePosition.arrayIndex = currentTranchePosition.arrayIndex + 1;
}
}
}
/**
* @notice check if user requires maturing
*
* @param _userGradual user gradual struct to update
* @param lastFinishedTrancheIndex index of last finished tranche index
* @return needsMaturing true if user needs maturing, else false
*/
function _isMaturing(UserGradual memory _userGradual, uint256 lastFinishedTrancheIndex)
private
pure
returns (bool)
{
return _userGradual.lastUpdatedTrancheIndex < lastFinishedTrancheIndex && _hasTranches(_userGradual);
}
/**
* @notice check if user gradual has any non-matured tranches
*
* @param _userGradual user gradual struct
* @return hasTranches true if user has non-matured tranches
*/
function _hasTranches(UserGradual memory _userGradual) private pure returns (bool hasTranches) {
if (_userGradual.oldestTranchePosition.arrayIndex > 0) {
hasTranches = true;
}
}
/* ---------- GRADUAL POWER: HELPER FUNCTIONS ---------- */
/**
* @notice return trimmed amount
* @dev `amount` is trimmed by `TRIM_SIZE`.
* This is done so the amount can be represented in 48bits.
* This still gives us enough accuracy so the core logic is not affected.
*
* @param amount amount to trim
* @return trimmedAmount amount divided by `TRIM_SIZE`
*/
function _trim(uint256 amount) private pure returns (uint48) {
return uint48(amount / TRIM_SIZE);
}
/**
* @notice return trimmed amount rounding up if any dust left
*
* @param amount amount to trim
* @return trimmedAmount amount divided by `TRIM_SIZE`, rounded up
*/
function _trimRoundUp(uint256 amount) private pure returns (uint48 trimmedAmount) {
trimmedAmount = _trim(amount);
if (_untrim(trimmedAmount) < amount) {
unchecked {
trimmedAmount++;
}
}
}
/**
* @notice untrim `trimmedAmount` in respect to `TRIM_SIZE`
*
* @param trimmedAmount amount previously trimemd
* @return untrimmedAmount untrimmed amount
*/
function _untrim(uint256 trimmedAmount) private pure returns (uint256) {
unchecked {
return trimmedAmount * TRIM_SIZE;
}
}
/**
* @notice calculates voting power from raw unmatured
*
* @param rawMaturingVotingPower raw maturing voting power amount
* @return maturingVotingPower actual maturing power amount
*/
function _getMaturingVotingPowerFromRaw(uint256 rawMaturingVotingPower) private pure returns (uint256) {
return rawMaturingVotingPower / FULL_POWER_TRANCHES_COUNT;
}
/**
* @notice Returns amount represented in raw unmatured value
* @dev used to substract fully-matured amount from raw unmatured, when amount matures
*
* @param amount matured amount
* @return asRawUnmatured `amount` multiplied by `FULL_POWER_TRANCHES_COUNT` (raw unmatured amount)
*/
function _getMaturedAsRawUnmaturedAmount(uint48 amount) private pure returns (uint56) {
unchecked {
return uint56(amount * FULL_POWER_TRANCHES_COUNT);
}
}
/* ========== OWNER FUNCTIONS ========== */
/**
* @notice Sets or resets the instant minter address
*
* Requirements:
*
* - the caller must be the owner of the contract
* - the minter must not be the zero address
*
* @param _minter address to set
* @param _set true to set, false to reset
*/
function setMinter(address _minter, bool _set) external onlyOwner {
require(_minter != address(0), "voSPOOL::setMinter: minter cannot be the zero address");
minters[_minter] = _set;
emit MinterSet(_minter, _set);
}
/**
* @notice Sets or resets the gradual minter address
*
* Requirements:
*
* - the caller must be the owner of the contract
* - the minter must not be the zero address
*
* @param _gradualMinter address to set
* @param _set true to set, false to reset
*/
function setGradualMinter(address _gradualMinter, bool _set) external onlyOwner {
require(_gradualMinter != address(0), "voSPOOL::setGradualMinter: gradual minter cannot be the zero address");
gradualMinters[_gradualMinter] = _set;
emit GradualMinterSet(_gradualMinter, _set);
}
/* ========== RESTRICTION FUNCTIONS ========== */
/**
* @notice Ensures the caller is the instant minter
*/
function _onlyMinter() private view {
require(minters[msg.sender], "voSPOOL::_onlyMinter: Insufficient Privileges");
}
/**
* @notice Ensures the caller is the gradual minter
*/
function _onlyGradualMinter() private view {
require(gradualMinters[msg.sender], "voSPOOL::_onlyGradualMinter: Insufficient Privileges");
}
/* ========== MODIFIERS ========== */
/**
* @notice Throws if the caller is not the instant miter
*/
modifier onlyMinter() {
_onlyMinter();
_;
}
/**
* @notice Throws if the caller is not the gradual minter
*/
modifier onlyGradualMinter() {
_onlyGradualMinter();
_;
}
/**
* @notice Update global gradual values
*/
modifier updateGradual() {
_updateGradual();
_;
}
/**
* @notice Update user gradual values
*/
modifier updateGradualUser(address user) {
_updateGradualUser(user);
_;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.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 `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.0 (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
pragma solidity 0.8.13;
import "./interfaces/ISpoolOwner.sol";
abstract contract SpoolOwnable {
ISpoolOwner internal immutable spoolOwner;
constructor(ISpoolOwner _spoolOwner) {
require(
address(_spoolOwner) != address(0),
"SpoolOwnable::constructor: Spool owner contract address cannot be 0"
);
spoolOwner = _spoolOwner;
}
function isSpoolOwner() internal view returns(bool) {
return spoolOwner.isSpoolOwner(msg.sender);
}
function _onlyOwner() internal view {
require(isSpoolOwner(), "SpoolOwnable::onlyOwner: Caller is not the Spool owner");
}
modifier onlyOwner() {
_onlyOwner();
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
interface ISpoolOwner {
function isSpoolOwner(address user) external view returns(bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
/* ========== STRUCTS ========== */
/**
* @notice global gradual struct
* @member totalMaturedVotingPower total fully-matured voting power amount
* @member totalMaturingAmount total maturing amount (amount of power that is accumulating every week for 1/156 of the amount)
* @member totalRawUnmaturedVotingPower total raw voting power still maturing every tranche (totalRawUnmaturedVotingPower/156 is its voting power)
* @member lastUpdatedTrancheIndex last (finished) tranche index global gradual has updated
*/
struct GlobalGradual {
uint48 totalMaturedVotingPower;
uint48 totalMaturingAmount;
uint56 totalRawUnmaturedVotingPower;
uint16 lastUpdatedTrancheIndex;
}
/**
* @notice user tranche position struct, pointing at user tranche
* @dev points at `userTranches` mapping
* @member arrayIndex points at `userTranches`
* @member position points at UserTranches position from zero to three (zero, one, two, or three)
*/
struct UserTranchePosition {
uint16 arrayIndex;
uint8 position;
}
/**
* @notice user gradual struct, similar to global gradual holds user gragual voting power values
* @dev points at `userTranches` mapping
* @member maturedVotingPower users fully-matured voting power amount
* @member maturingAmount users maturing amount
* @member rawUnmaturedVotingPower users raw voting power still maturing every tranche
* @member oldestTranchePosition UserTranchePosition pointing at the oldest unmatured UserTranche
* @member latestTranchePosition UserTranchePosition pointing at the latest unmatured UserTranche
* @member lastUpdatedTrancheIndex last (finished) tranche index user gradual has updated
*/
struct UserGradual {
uint48 maturedVotingPower; // matured voting amount, power accumulated and older than FULL_POWER_TIME, not accumulating anymore
uint48 maturingAmount; // total maturing amount (also maximum matured)
uint56 rawUnmaturedVotingPower; // current user raw unmatured voting power (increases every new tranche), actual unmatured voting power can be calculated as unmaturedVotingPower / FULL_POWER_TRANCHES_COUNT
UserTranchePosition oldestTranchePosition; // if arrayIndex is 0, user has no tranches (even if `latestTranchePosition` is not empty)
UserTranchePosition latestTranchePosition; // can only increment, in case of tranche removal, next time user gradually mints we point at tranche at next position
uint16 lastUpdatedTrancheIndex;
}
/**
* @title Spool DAO Voting Token interface
*/
interface IVoSPOOL {
/* ========== FUNCTIONS ========== */
function mint(address, uint256) external;
function burn(address, uint256) external;
function mintGradual(address, uint256) external;
function burnGradual(
address,
uint256,
bool
) external;
function updateVotingPower() external;
function updateUserVotingPower(address user) external;
function getTotalGradualVotingPower() external returns (uint256);
function getUserGradualVotingPower(address user) external returns (uint256);
function getNotUpdatedUserGradual(address user) external view returns (UserGradual memory);
function getNotUpdatedGlobalGradual() external view returns (GlobalGradual memory);
function getCurrentTrancheIndex() external view returns (uint16);
function getLastFinishedTrancheIndex() external view returns (uint16);
/* ========== EVENTS ========== */
event Minted(address indexed recipient, uint256 amount);
event Burned(address indexed source, uint256 amount);
event GradualMinted(address indexed recipient, uint256 amount);
event GradualBurned(address indexed source, uint256 amount, bool burnAll);
event GlobalGradualUpdated(
uint16 indexed lastUpdatedTrancheIndex,
uint48 totalMaturedVotingPower,
uint48 totalMaturingAmount,
uint56 totalRawUnmaturedVotingPower
);
event UserGradualUpdated(
address indexed user,
uint16 indexed lastUpdatedTrancheIndex,
uint48 maturedVotingPower,
uint48 maturingAmount,
uint56 rawUnmaturedVotingPower
);
event MinterSet(address indexed minter, bool set);
event GradualMinterSet(address indexed minter, bool set);
} | Execution of function is prohibited to disallow token movement/ | function transfer(address, uint256) external pure override returns (bool) {
revert("voSPOOL::transfer: Prohibited Action");
}
| 233,158 |
./partial_match/42/0x53AF86B01ca8668D7a5F52E3361D4Bc7A331bfdf/sources/BirdCore.sol | User supplies assets into the market and receives bTokens in exchange Assumes interest has already been accrued up to the current block minter The address of the account which is supplying the assets mintAmount The amount of the underlying asset to supply return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount./ Fail if mint not allowed / Verify market's block number equals current block number / | function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
uint allowed = bController.mintAllowed(address(this), minter, mintAmount);
emit AllowedTestEvent(minter, address(this), allowed);
if (allowed != 0) {
return (failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.MINT_BCONTROLLER_REJECTION, allowed), 0);
}
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
accountTokens[minter] = vars.accountTokensNew;
emit Transfer(address(this), minter, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
| 8,918,198 |
// File: canonical-weth/contracts/WETH9.sol
// Copyright (C) 2015, 2016, 2017 Dapphub
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity >=0.4.22 <0.6;
contract WETH9 {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
function() external payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
msg.sender.transfer(wad);
emit Withdrawal(msg.sender, wad);
}
function totalSupply() public view returns (uint) {
return address(this).balance;
}
function approve(address guy, uint wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
emit Transfer(src, dst, wad);
return true;
}
}
/*
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.5.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].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// 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;
}
}
// 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/protocol/lib/Require.sol
/*
Copyright 2019 dYdX Trading 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.5.7;
pragma experimental ABIEncoderV2;
/**
* @title Require
* @author dYdX
*
* Stringifies parameters to pretty-print revert messages. Costs more gas than regular require()
*/
library Require {
// ============ Constants ============
uint256 constant ASCII_ZERO = 48; // '0'
uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10
uint256 constant ASCII_LOWER_EX = 120; // 'x'
bytes2 constant COLON = 0x3a20; // ': '
bytes2 constant COMMA = 0x2c20; // ', '
bytes2 constant LPAREN = 0x203c; // ' <'
byte constant RPAREN = 0x3e; // '>'
uint256 constant FOUR_BIT_MASK = 0xf;
// ============ Library Functions ============
function that(
bool must,
bytes32 file,
bytes32 reason
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason)
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
// ============ Private Functions ============
function stringifyTruncated(
bytes32 input
)
private
pure
returns (bytes memory)
{
// put the input bytes into the result
bytes memory result = abi.encodePacked(input);
// determine the length of the input by finding the location of the last non-zero byte
for (uint256 i = 32; i > 0; ) {
// reverse-for-loops with unsigned integer
/* solium-disable-next-line security/no-modify-for-iter-var */
i--;
// find the last non-zero byte in order to determine the length
if (result[i] != 0) {
uint256 length = i + 1;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
mstore(result, length) // r.length = length;
}
return result;
}
}
// all bytes are zero
return new bytes(0);
}
function stringify(
uint256 input
)
private
pure
returns (bytes memory)
{
if (input == 0) {
return "0";
}
// get the final string length
uint256 j = input;
uint256 length;
while (j != 0) {
length++;
j /= 10;
}
// allocate the string
bytes memory bstr = new bytes(length);
// populate the string starting with the least-significant character
j = input;
for (uint256 i = length; i > 0; ) {
// reverse-for-loops with unsigned integer
/* solium-disable-next-line security/no-modify-for-iter-var */
i--;
// take last decimal digit
bstr[i] = byte(uint8(ASCII_ZERO + (j % 10)));
// remove the last decimal digit
j /= 10;
}
return bstr;
}
function stringify(
address input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
// addresses are "0x" followed by 20 bytes of data which take up 2 characters each
bytes memory result = new bytes(42);
// populate the result with "0x"
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 20; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[41 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[40 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function stringify(
bytes32 input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
// bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each
bytes memory result = new bytes(66);
// populate the result with "0x"
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 32; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[65 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[64 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function char(
uint256 input
)
private
pure
returns (byte)
{
// return ASCII digit (0-9)
if (input < 10) {
return byte(uint8(input + ASCII_ZERO));
}
// return ASCII letter (a-f)
return byte(uint8(input + ASCII_RELATIVE_ZERO));
}
}
// File: contracts/protocol/lib/Math.sol
/*
Copyright 2019 dYdX Trading 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.5.7;
/**
* @title Math
* @author dYdX
*
* Library for non-standard Math functions
*/
library Math {
using SafeMath for uint256;
// ============ Constants ============
bytes32 constant FILE = "Math";
// ============ Library Functions ============
/*
* Return target * (numerator / denominator).
*/
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
/*
* Return target * (numerator / denominator), but rounded up.
*/
function getPartialRoundUp(
uint256 target,
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
if (target == 0 || numerator == 0) {
// SafeMath will check for zero denominator
return SafeMath.div(0, denominator);
}
return target.mul(numerator).sub(1).div(denominator).add(1);
}
function getPartialRoundHalfUp(
uint256 target,
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
if (target == 0 || numerator == 0) {
// SafeMath will check for zero denominator
return SafeMath.div(0, denominator);
}
uint result = target.mul(numerator);
// round the denominator comparator up to ensure a fair comparison is done on the `result`'s modulo.
// For example, 51 / 103 == 0; 51 % 103 == 51; ((103 - 1) / 2) + 1 == 52; 51 < 52, therefore no round up
return result.div(denominator).add(result.mod(denominator) >= denominator.sub(1).div(2).add(1) ? 1 : 0);
}
function to128(
uint256 number
)
internal
pure
returns (uint128)
{
uint128 result = uint128(number);
Require.that(
result == number,
FILE,
"Unsafe cast to uint128",
number
);
return result;
}
function to96(
uint256 number
)
internal
pure
returns (uint96)
{
uint96 result = uint96(number);
Require.that(
result == number,
FILE,
"Unsafe cast to uint96",
number
);
return result;
}
function to32(
uint256 number
)
internal
pure
returns (uint32)
{
uint32 result = uint32(number);
Require.that(
result == number,
FILE,
"Unsafe cast to uint32",
number
);
return result;
}
function min(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
function max(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a > b ? a : b;
}
}
// File: contracts/protocol/lib/Types.sol
/*
Copyright 2019 dYdX Trading 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.5.7;
/**
* @title Types
* @author dYdX
*
* Library for interacting with the basic structs used in DolomiteMargin
*/
library Types {
using Math for uint256;
// ============ Permission ============
struct OperatorArg {
address operator;
bool trusted;
}
// ============ AssetAmount ============
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
// ============ Par (Principal Amount) ============
// Total borrow and supply values for a market
struct TotalPar {
uint128 borrow;
uint128 supply;
}
// Individual principal amount for an account
struct Par {
bool sign; // true if positive
uint128 value;
}
function zeroPar()
internal
pure
returns (Par memory)
{
return Par({
sign: false,
value: 0
});
}
function sub(
Par memory a,
Par memory b
)
internal
pure
returns (Par memory)
{
return add(a, negative(b));
}
function add(
Par memory a,
Par memory b
)
internal
pure
returns (Par memory)
{
Par memory result;
if (a.sign == b.sign) {
result.sign = a.sign;
result.value = SafeMath.add(a.value, b.value).to128();
} else {
if (a.value >= b.value) {
result.sign = a.sign;
result.value = SafeMath.sub(a.value, b.value).to128();
} else {
result.sign = b.sign;
result.value = SafeMath.sub(b.value, a.value).to128();
}
}
return result;
}
function equals(
Par memory a,
Par memory b
)
internal
pure
returns (bool)
{
if (a.value == b.value) {
if (a.value == 0) {
return true;
}
return a.sign == b.sign;
}
return false;
}
function negative(
Par memory a
)
internal
pure
returns (Par memory)
{
return Par({
sign: !a.sign,
value: a.value
});
}
function isNegative(
Par memory a
)
internal
pure
returns (bool)
{
return !a.sign && a.value > 0;
}
function isPositive(
Par memory a
)
internal
pure
returns (bool)
{
return a.sign && a.value > 0;
}
function isZero(
Par memory a
)
internal
pure
returns (bool)
{
return a.value == 0;
}
function isLessThanZero(
Par memory a
)
internal
pure
returns (bool)
{
return a.value > 0 && !a.sign;
}
function isGreaterThanOrEqualToZero(
Par memory a
)
internal
pure
returns (bool)
{
return isZero(a) || a.sign;
}
// ============ Wei (Token Amount) ============
// Individual token amount for an account
struct Wei {
bool sign; // true if positive
uint256 value;
}
function zeroWei()
internal
pure
returns (Wei memory)
{
return Wei({
sign: false,
value: 0
});
}
function sub(
Wei memory a,
Wei memory b
)
internal
pure
returns (Wei memory)
{
return add(a, negative(b));
}
function add(
Wei memory a,
Wei memory b
)
internal
pure
returns (Wei memory)
{
Wei memory result;
if (a.sign == b.sign) {
result.sign = a.sign;
result.value = SafeMath.add(a.value, b.value);
} else {
if (a.value >= b.value) {
result.sign = a.sign;
result.value = SafeMath.sub(a.value, b.value);
} else {
result.sign = b.sign;
result.value = SafeMath.sub(b.value, a.value);
}
}
return result;
}
function equals(
Wei memory a,
Wei memory b
)
internal
pure
returns (bool)
{
if (a.value == b.value) {
if (a.value == 0) {
return true;
}
return a.sign == b.sign;
}
return false;
}
function negative(
Wei memory a
)
internal
pure
returns (Wei memory)
{
return Wei({
sign: !a.sign,
value: a.value
});
}
function isNegative(
Wei memory a
)
internal
pure
returns (bool)
{
return !a.sign && a.value > 0;
}
function isPositive(
Wei memory a
)
internal
pure
returns (bool)
{
return a.sign && a.value > 0;
}
function isZero(
Wei memory a
)
internal
pure
returns (bool)
{
return a.value == 0;
}
}
// File: contracts/protocol/lib/EnumerableSet.sol
/*
Copyright 2021 Dolomite.
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.5.7;
library EnumerableSet {
struct Set {
// Storage of set values
uint256[] _values;
// Value to the index in `_values` array, plus 1 because index 0 means a value is not in the set.
mapping(uint256 => uint256) _valueToIndexMap;
}
/**
* @dev Add a value to a set. O(1).
*
* @return true if the value was added to the set, that is if it was not already present.
*/
function add(Set storage set, uint256 value) internal 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._valueToIndexMap[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* @return true if the value was removed from the set, that is if it was present.
*/
function remove(Set storage set, uint256 value) internal returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._valueToIndexMap[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) {
uint256 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._valueToIndexMap[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
}
// Delete the slot where the moved value was stored, which is the last index
set._values.pop();
// Delete the index for the deleted slot
delete set._valueToIndexMap[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Set storage set, uint256 value) internal view returns (bool) {
return set._valueToIndexMap[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(Set storage set) internal view returns (uint256) {
return set._values.length;
}
/**
* @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) internal view returns (uint256[] memory) {
return set._values;
}
}
// File: contracts/protocol/lib/Account.sol
/*
Copyright 2019 dYdX Trading 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.5.7;
/**
* @title Account
* @author dYdX
*
* Library of structs and functions that represent an account
*/
library Account {
// ============ Enums ============
/*
* Most-recently-cached account status.
*
* Normal: Can only be liquidated if the account values are violating the global margin-ratio.
* Liquid: Can be liquidated no matter the account values.
* Can be vaporized if there are no more positive account values.
* Vapor: Has only negative (or zeroed) account values. Can be vaporized.
*
*/
enum Status {
Normal,
Liquid,
Vapor
}
// ============ Structs ============
// Represents the unique key that specifies an account
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
// The complete storage for any account
struct Storage {
Status status;
uint32 numberOfMarketsWithBorrow;
EnumerableSet.Set marketsWithNonZeroBalanceSet;
mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal
}
// ============ Library Functions ============
function equals(
Info memory a,
Info memory b
)
internal
pure
returns (bool)
{
return a.owner == b.owner && a.number == b.number;
}
}
// File: contracts/protocol/lib/Actions.sol
/*
Copyright 2019 dYdX Trading 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.5.7;
/**
* @title Actions
* @author dYdX
*
* Library that defines and parses valid Actions
*/
library Actions {
// ============ Constants ============
bytes32 constant FILE = "Actions";
// ============ Enums ============
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (externally)
Sell, // sell an amount of some token (externally)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
enum AccountLayout {
OnePrimary,
TwoPrimary,
PrimaryAndSecondary
}
enum MarketLayout {
ZeroMarkets,
OneMarket,
TwoMarkets
}
// ============ Structs ============
/*
* Arguments that are passed to DolomiteMargin in an ordered list as part of a single operation.
* Each ActionArgs has an actionType which specifies which action struct that this data will be
* parsed into before being processed.
*/
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
// ============ Action Types ============
/*
* Moves tokens from an address to DolomiteMargin. Can either repay a borrow or provide additional supply.
*/
struct DepositArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address from;
}
/*
* Moves tokens from DolomiteMargin to another address. Can either borrow tokens or reduce the amount
* previously supplied.
*/
struct WithdrawArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address to;
}
/*
* Transfers balance between two accounts. The msg.sender must be an operator for both accounts.
* The amount field applies to accountOne.
* This action does not require any token movement since the trade is done internally to DolomiteMargin.
*/
struct TransferArgs {
Types.AssetAmount amount;
Account.Info accountOne;
Account.Info accountTwo;
uint256 market;
}
/*
* Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the
* specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field
* applies to the makerMarket.
*/
struct BuyArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 makerMarket;
uint256 takerMarket;
address exchangeWrapper;
bytes orderData;
}
/*
* Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the
* specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies
* to the takerMarket.
*/
struct SellArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 takerMarket;
uint256 makerMarket;
address exchangeWrapper;
bytes orderData;
}
/*
* Trades balances between two accounts using any external contract that implements the
* AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for
* which it is trading on-behalf-of). The amount field applies to the makerAccount and the
* inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will
* quote a change for the makerAccount in the outputMarket (or will disallow the trade).
* This action does not require any token movement since the trade is done internally to DolomiteMargin.
*/
struct TradeArgs {
Types.AssetAmount amount;
Account.Info takerAccount;
Account.Info makerAccount;
uint256 inputMarket;
uint256 outputMarket;
address autoTrader;
bytes tradeData;
}
/*
* Each account must maintain a certain margin-ratio (specified globally). If the account falls
* below this margin-ratio, it can be liquidated by any other account. This allows anyone else
* (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in
* exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined
* by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an
* account also sets a flag on the account that the account is being liquidated. This allows
* anyone to continue liquidating the account until there are no more borrows being taken by the
* liquidating account. Liquidators do not have to liquidate the entire account all at once but
* can liquidate as much as they choose. The liquidating flag allows liquidators to continue
* liquidating the account even if it becomes collateralized through partial liquidation or
* price movement.
*/
struct LiquidateArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info liquidAccount;
uint256 owedMarket;
uint256 heldMarket;
}
/*
* Similar to liquidate, but vaporAccounts are accounts that have only negative balances remaining. The arbitrageur
* pays back the negative asset (owedMarket) of the vaporAccount in exchange for a collateral asset (heldMarket) at
* a favorable spread. However, since the liquidAccount has no collateral assets, the collateral must come from
* DolomiteMargin's excess tokens.
*/
struct VaporizeArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info vaporAccount;
uint256 owedMarket;
uint256 heldMarket;
}
/*
* Passes arbitrary bytes of data to an external contract that implements the Callee interface.
* Does not change any asset amounts. This function may be useful for setting certain variables
* on layer-two contracts for certain accounts without having to make a separate Ethereum
* transaction for doing so. Also, the second-layer contracts can ensure that the call is coming
* from an operator of the particular account.
*/
struct CallArgs {
Account.Info account;
address callee;
bytes data;
}
// ============ Helper Functions ============
function getMarketLayout(
ActionType actionType
)
internal
pure
returns (MarketLayout)
{
if (
actionType == Actions.ActionType.Deposit
|| actionType == Actions.ActionType.Withdraw
|| actionType == Actions.ActionType.Transfer
) {
return MarketLayout.OneMarket;
}
else if (actionType == Actions.ActionType.Call) {
return MarketLayout.ZeroMarkets;
}
return MarketLayout.TwoMarkets;
}
function getAccountLayout(
ActionType actionType
)
internal
pure
returns (AccountLayout)
{
if (
actionType == Actions.ActionType.Transfer
|| actionType == Actions.ActionType.Trade
) {
return AccountLayout.TwoPrimary;
} else if (
actionType == Actions.ActionType.Liquidate
|| actionType == Actions.ActionType.Vaporize
) {
return AccountLayout.PrimaryAndSecondary;
}
return AccountLayout.OnePrimary;
}
// ============ Parsing Functions ============
function parseDepositArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (DepositArgs memory)
{
return DepositArgs({
amount: args.amount,
account: accounts[args.accountId],
market: args.primaryMarketId,
from: args.otherAddress
});
}
function parseWithdrawArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (WithdrawArgs memory)
{
return WithdrawArgs({
amount: args.amount,
account: accounts[args.accountId],
market: args.primaryMarketId,
to: args.otherAddress
});
}
function parseTransferArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (TransferArgs memory)
{
return TransferArgs({
amount: args.amount,
accountOne: accounts[args.accountId],
accountTwo: accounts[args.otherAccountId],
market: args.primaryMarketId
});
}
function parseBuyArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (BuyArgs memory)
{
return BuyArgs({
amount: args.amount,
account: accounts[args.accountId],
makerMarket: args.primaryMarketId,
takerMarket: args.secondaryMarketId,
exchangeWrapper: args.otherAddress,
orderData: args.data
});
}
function parseSellArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (SellArgs memory)
{
return SellArgs({
amount: args.amount,
account: accounts[args.accountId],
takerMarket: args.primaryMarketId,
makerMarket: args.secondaryMarketId,
exchangeWrapper: args.otherAddress,
orderData: args.data
});
}
function parseTradeArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (TradeArgs memory)
{
return TradeArgs({
amount: args.amount,
takerAccount: accounts[args.accountId],
makerAccount: accounts[args.otherAccountId],
inputMarket: args.primaryMarketId,
outputMarket: args.secondaryMarketId,
autoTrader: args.otherAddress,
tradeData: args.data
});
}
function parseLiquidateArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (LiquidateArgs memory)
{
return LiquidateArgs({
amount: args.amount,
solidAccount: accounts[args.accountId],
liquidAccount: accounts[args.otherAccountId],
owedMarket: args.primaryMarketId,
heldMarket: args.secondaryMarketId
});
}
function parseVaporizeArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (VaporizeArgs memory)
{
return VaporizeArgs({
amount: args.amount,
solidAccount: accounts[args.accountId],
vaporAccount: accounts[args.otherAccountId],
owedMarket: args.primaryMarketId,
heldMarket: args.secondaryMarketId
});
}
function parseCallArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (CallArgs memory)
{
return CallArgs({
account: accounts[args.accountId],
callee: args.otherAddress,
data: args.data
});
}
}
// File: contracts/protocol/lib/Decimal.sol
/*
Copyright 2019 dYdX Trading 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.5.7;
/**
* @title Decimal
* @author dYdX
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMath for uint256;
// ============ Constants ============
uint256 constant BASE = 10**18;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Functions ============
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
function onePlus(
D256 memory d
)
internal
pure
returns (D256 memory)
{
return D256({ value: d.value.add(BASE) });
}
function mul(
uint256 target,
D256 memory d
)
internal
pure
returns (uint256)
{
return Math.getPartial(target, d.value, BASE);
}
function div(
uint256 target,
D256 memory d
)
internal
pure
returns (uint256)
{
return Math.getPartial(target, BASE, d.value);
}
}
// File: contracts/protocol/lib/Time.sol
/*
Copyright 2019 dYdX Trading 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.5.7;
/**
* @title Time
* @author dYdX
*
* Library for dealing with time, assuming timestamps fit within 32 bits (valid until year 2106)
*/
library Time {
// ============ Library Functions ============
function currentTime()
internal
view
returns (uint32)
{
return Math.to32(block.timestamp);
}
}
// File: contracts/protocol/lib/Interest.sol
/*
Copyright 2019 dYdX Trading 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.5.7;
/**
* @title Interest
* @author dYdX
*
* Library for managing the interest rate and interest indexes of DolomiteMargin
*/
library Interest {
using Math for uint256;
using SafeMath for uint256;
// ============ Constants ============
bytes32 constant FILE = "Interest";
uint64 constant BASE = 10**18;
// ============ Structs ============
struct Rate {
uint256 value;
}
struct Index {
uint96 borrow;
uint96 supply;
uint32 lastUpdate;
}
// ============ Library Functions ============
/**
* Get a new market Index based on the old index and market interest rate.
* Calculate interest for borrowers by using the formula rate * time. Approximates
* continuously-compounded interest when called frequently, but is much more
* gas-efficient to calculate. For suppliers, the interest rate is adjusted by the earningsRate,
* then prorated across all suppliers.
*
* @param index The old index for a market
* @param rate The current interest rate of the market
* @param totalPar The total supply and borrow par values of the market
* @param earningsRate The portion of the interest that is forwarded to the suppliers
* @return The updated index for a market
*/
function calculateNewIndex(
Index memory index,
Rate memory rate,
Types.TotalPar memory totalPar,
Decimal.D256 memory earningsRate
)
internal
view
returns (Index memory)
{
(
Types.Wei memory supplyWei,
Types.Wei memory borrowWei
) = totalParToWei(totalPar, index);
// get interest increase for borrowers
uint32 currentTime = Time.currentTime();
uint256 borrowInterest = rate.value.mul(uint256(currentTime).sub(index.lastUpdate));
// get interest increase for suppliers
uint256 supplyInterest;
if (Types.isZero(supplyWei)) {
supplyInterest = 0;
} else {
supplyInterest = Decimal.mul(borrowInterest, earningsRate);
if (borrowWei.value < supplyWei.value) {
supplyInterest = Math.getPartial(supplyInterest, borrowWei.value, supplyWei.value);
}
}
assert(supplyInterest <= borrowInterest);
return Index({
borrow: Math.getPartial(index.borrow, borrowInterest, BASE).add(index.borrow).to96(),
supply: Math.getPartial(index.supply, supplyInterest, BASE).add(index.supply).to96(),
lastUpdate: currentTime
});
}
function newIndex()
internal
view
returns (Index memory)
{
return Index({
borrow: BASE,
supply: BASE,
lastUpdate: Time.currentTime()
});
}
/*
* Convert a principal amount to a token amount given an index.
*/
function parToWei(
Types.Par memory input,
Index memory index
)
internal
pure
returns (Types.Wei memory)
{
uint256 inputValue = uint256(input.value);
if (input.sign) {
return Types.Wei({
sign: true,
value: inputValue.getPartialRoundHalfUp(index.supply, BASE)
});
} else {
return Types.Wei({
sign: false,
value: inputValue.getPartialRoundUp(index.borrow, BASE)
});
}
}
/*
* Convert a token amount to a principal amount given an index.
*/
function weiToPar(
Types.Wei memory input,
Index memory index
)
internal
pure
returns (Types.Par memory)
{
if (input.sign) {
return Types.Par({
sign: true,
value: input.value.getPartialRoundHalfUp(BASE, index.supply).to128()
});
} else {
return Types.Par({
sign: false,
value: input.value.getPartialRoundUp(BASE, index.borrow).to128()
});
}
}
/*
* Convert the total supply and borrow principal amounts of a market to total supply and borrow
* token amounts.
*/
function totalParToWei(
Types.TotalPar memory totalPar,
Index memory index
)
internal
pure
returns (Types.Wei memory, Types.Wei memory)
{
Types.Par memory supplyPar = Types.Par({
sign: true,
value: totalPar.supply
});
Types.Par memory borrowPar = Types.Par({
sign: false,
value: totalPar.borrow
});
Types.Wei memory supplyWei = parToWei(supplyPar, index);
Types.Wei memory borrowWei = parToWei(borrowPar, index);
return (supplyWei, borrowWei);
}
}
// File: contracts/protocol/interfaces/IInterestSetter.sol
/*
Copyright 2019 dYdX Trading 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.5.7;
/**
* @title IInterestSetter
* @author dYdX
*
* Interface that Interest Setters for DolomiteMargin must implement in order to report interest rates.
*/
interface IInterestSetter {
// ============ Public Functions ============
/**
* Get the interest rate of a token given some borrowed and supplied amounts
*
* @param token The address of the ERC20 token for the market
* @param borrowWei The total borrowed token amount for the market
* @param supplyWei The total supplied token amount for the market
* @return The interest rate per second
*/
function getInterestRate(
address token,
uint256 borrowWei,
uint256 supplyWei
)
external
view
returns (Interest.Rate memory);
}
// File: contracts/protocol/lib/Monetary.sol
/*
Copyright 2019 dYdX Trading 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.5.7;
/**
* @title Monetary
* @author dYdX
*
* Library for types involving money
*/
library Monetary {
/*
* The price of a base-unit of an asset. Has `36 - token.decimals` decimals
*/
struct Price {
uint256 value;
}
/*
* Total value of an some amount of an asset. Equal to (price * amount). Has 36 decimals.
*/
struct Value {
uint256 value;
}
}
// File: contracts/protocol/interfaces/IPriceOracle.sol
/*
Copyright 2019 dYdX Trading 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.5.7;
/**
* @title IPriceOracle
* @author dYdX
*
* Interface that Price Oracles for DolomiteMargin must implement in order to report prices.
*/
contract IPriceOracle {
// ============ Constants ============
uint256 public constant ONE_DOLLAR = 10 ** 36;
// ============ Public Functions ============
/**
* Get the price of a token
*
* @param token The ERC20 token address of the market
* @return The USD price of a base unit of the token, then multiplied by 10^36.
* So a USD-stable coin with 18 decimal places would return 10^18.
* This is the price of the base unit rather than the price of a "human-readable"
* token amount. Every ERC20 may have a different number of decimals.
*/
function getPrice(
address token
)
public
view
returns (Monetary.Price memory);
}
// File: contracts/protocol/lib/Cache.sol
/*
Copyright 2019 dYdX Trading 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.5.7;
/**
* @title Cache
* @author dYdX
*
* Library for caching information about markets
*/
library Cache {
// ============ Constants ============
bytes32 internal constant FILE = "Cache";
uint internal constant ONE = 1;
uint256 internal constant MAX_UINT_BITS = 256;
// ============ Structs ============
struct MarketInfo {
uint marketId;
address token;
bool isClosing;
uint128 borrowPar;
Monetary.Price price;
}
struct MarketCache {
MarketInfo[] markets;
uint256[] marketBitmaps;
uint256 marketsLength;
}
// ============ Setter Functions ============
/**
* Initialize an empty cache for some given number of total markets.
*/
function create(
uint256 numMarkets
)
internal
pure
returns (MarketCache memory)
{
return MarketCache({
markets: new MarketInfo[](0),
marketBitmaps: new uint[]((numMarkets / MAX_UINT_BITS) + ONE),
marketsLength: 0
});
}
// ============ Getter Functions ============
function getNumMarkets(
MarketCache memory cache
)
internal
pure
returns (uint256)
{
return cache.markets.length;
}
function hasMarket(
MarketCache memory cache,
uint256 marketId
)
internal
pure
returns (bool)
{
uint bucketIndex = marketId / MAX_UINT_BITS;
uint indexFromRight = marketId % MAX_UINT_BITS;
uint bit = cache.marketBitmaps[bucketIndex] & (ONE << indexFromRight);
return bit > 0;
}
function get(
MarketCache memory cache,
uint256 marketId
)
internal
pure
returns (MarketInfo memory)
{
Require.that(
cache.markets.length > 0,
FILE,
"not initialized"
);
return _getInternal(
cache.markets,
0,
cache.marketsLength,
marketId
);
}
function set(
MarketCache memory cache,
uint256 marketId
)
internal
pure
{
// Devs should not be able to call this function once the `markets` array has been initialized (non-zero length)
Require.that(
cache.markets.length == 0,
FILE,
"already initialized"
);
uint bucketIndex = marketId / MAX_UINT_BITS;
uint indexFromRight = marketId % MAX_UINT_BITS;
cache.marketBitmaps[bucketIndex] |= (ONE << indexFromRight);
cache.marketsLength += 1;
}
function getAtIndex(
MarketCache memory cache,
uint256 index
)
internal
pure
returns (MarketInfo memory)
{
Require.that(
index < cache.markets.length,
FILE,
"invalid index",
index,
cache.markets.length
);
return cache.markets[index];
}
// solium-disable security/no-assign-params
function getLeastSignificantBit(uint256 x) internal pure returns (uint) {
// gas usage peaks at 350 per call
uint lsb = 255;
if (x & uint128(-1) > 0) {
lsb -= 128;
} else {
x >>= 128;
}
if (x & uint64(-1) > 0) {
lsb -= 64;
} else {
x >>= 64;
}
if (x & uint32(-1) > 0) {
lsb -= 32;
} else {
x >>= 32;
}
if (x & uint16(-1) > 0) {
lsb -= 16;
} else {
x >>= 16;
}
if (x & uint8(-1) > 0) {
lsb -= 8;
} else {
x >>= 8;
}
if (x & 0xf > 0) {
lsb -= 4;
} else {
x >>= 4;
}
if (x & 0x3 > 0) {
lsb -= 2;
} else {
x >>= 2;
}
if (x & 0x1 > 0) {
lsb -= 1;
}
// solium-enable security/no-assign-params
return lsb;
}
// ============ Private Functions ============
function _getInternal(
MarketInfo[] memory data,
uint beginInclusive,
uint endExclusive,
uint marketId
) private pure returns (MarketInfo memory) {
uint len = endExclusive - beginInclusive;
if (len == 0 || (len == ONE && data[beginInclusive].marketId != marketId)) {
revert("Cache: item not found");
}
uint mid = beginInclusive + len / 2;
uint midMarketId = data[mid].marketId;
if (marketId < midMarketId) {
return _getInternal(
data,
beginInclusive,
mid,
marketId
);
} else if (marketId > midMarketId) {
return _getInternal(
data,
mid + 1,
endExclusive,
marketId
);
} else {
return data[mid];
}
}
}
// 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: contracts/protocol/interfaces/IERC20Detailed.sol
/*
Copyright 2019 dYdX Trading 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.5.7;
/**
* @title IERC20
* @author dYdX
*
* Interface for using ERC20 Tokens. We have to use a special interface to call ERC20 functions so
* that we don't automatically revert when calling non-compliant tokens that have no return value for
* transfer(), transferFrom(), or approve().
*/
contract IERC20Detailed is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// File: contracts/protocol/lib/Token.sol
/*
Copyright 2019 dYdX Trading 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.5.7;
/**
* @title Token
* @author dYdX
*
* This library contains basic functions for interacting with ERC20 tokens. Modified to work with
* tokens that don't adhere strictly to the ERC20 standard (for example tokens that don't return a
* boolean value on success).
*/
library Token {
// ============ Library Functions ============
function transfer(
address token,
address to,
uint256 amount
)
internal
{
if (amount == 0 || to == address(this)) {
return;
}
_callOptionalReturn(
token,
abi.encodeWithSelector(IERC20Detailed(token).transfer.selector, to, amount),
"Token: transfer failed"
);
}
function transferFrom(
address token,
address from,
address to,
uint256 amount
)
internal
{
if (amount == 0 || to == from) {
return;
}
// solium-disable arg-overflow
_callOptionalReturn(
token,
abi.encodeWithSelector(IERC20Detailed(token).transferFrom.selector, from, to, amount),
"Token: transferFrom failed"
);
// solium-enable arg-overflow
}
// ============ Private Functions ============
function _callOptionalReturn(address token, bytes memory data, string memory error) 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 contain contract code. Not needed since tokens are manually added
// 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.
// solium-disable-next-line security/no-low-level-calls
(bool success, bytes memory returnData) = token.call(data);
require(success, error);
if (returnData.length > 0) {
// Return data is optional
require(abi.decode(returnData, (bool)), error);
}
}
}
// File: contracts/protocol/lib/Storage.sol
/*
Copyright 2019 dYdX Trading 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.5.7;
/**
* @title Storage
* @author dYdX
*
* Functions for reading, writing, and verifying state in DolomiteMargin
*/
library Storage {
using Cache for Cache.MarketCache;
using Storage for Storage.State;
using Math for uint256;
using Types for Types.Par;
using Types for Types.Wei;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.Set;
// ============ Constants ============
bytes32 internal constant FILE = "Storage";
uint256 internal constant ONE = 1;
uint256 internal constant MAX_UINT_BITS = 256;
// ============ Structs ============
// All information necessary for tracking a market
struct Market {
// Contract address of the associated ERC20 token
address token;
// Whether additional borrows are allowed for this market
bool isClosing;
// Whether this market can be removed and its ID can be recycled and reused
bool isRecyclable;
// Total aggregated supply and borrow amount of the entire market
Types.TotalPar totalPar;
// Interest index of the market
Interest.Index index;
// Contract address of the price oracle for this market
IPriceOracle priceOracle;
// Contract address of the interest setter for this market
IInterestSetter interestSetter;
// Multiplier on the marginRatio for this market, IE 5% (0.05 * 1e18). This number increases the market's
// required collateralization by: reducing the user's supplied value (in terms of dollars) for this market and
// increasing its borrowed value. This is done through the following operation:
// `suppliedWei = suppliedWei + (assetValueForThisMarket / (1 + marginPremium))`
// This number increases the user's borrowed wei by multiplying it by:
// `borrowedWei = borrowedWei + (assetValueForThisMarket * (1 + marginPremium))`
Decimal.D256 marginPremium;
// Multiplier on the liquidationSpread for this market, IE 20% (0.2 * 1e18). This number increases the
// `liquidationSpread` using the following formula:
// `liquidationSpread = liquidationSpread * (1 + spreadPremium)`
// NOTE: This formula is applied up to two times - one for each market whose spreadPremium is greater than 0
// (when performing a liquidation between two markets)
Decimal.D256 spreadPremium;
}
// The global risk parameters that govern the health and security of the system
struct RiskParams {
// Required ratio of over-collateralization
Decimal.D256 marginRatio;
// Percentage penalty incurred by liquidated accounts
Decimal.D256 liquidationSpread;
// Percentage of the borrower's interest fee that gets passed to the suppliers
Decimal.D256 earningsRate;
// The minimum absolute borrow value of an account
// There must be sufficient incentivize to liquidate undercollateralized accounts
Monetary.Value minBorrowedValue;
}
// The maximum RiskParam values that can be set
struct RiskLimits {
// The highest that the ratio can be for liquidating under-water accounts
uint64 marginRatioMax;
// The highest that the liquidation rewards can be when a liquidator liquidates an account
uint64 liquidationSpreadMax;
// The highest that the supply APR can be for a market, as a proportion of the borrow rate. Meaning, a rate of
// 100% (1e18) would give suppliers all of the interest that borrowers are paying. A rate of 90% would give
// suppliers 90% of the interest that borrowers pay.
uint64 earningsRateMax;
uint64 marginPremiumMax;
uint64 spreadPremiumMax;
uint128 minBorrowedValueMax;
}
// The entire storage state of DolomiteMargin
struct State {
// number of markets
uint256 numMarkets;
// marketId => Market
mapping (uint256 => Market) markets;
mapping (address => uint256) tokenToMarketId;
mapping(uint256 => uint256) recycledMarketIds;
// owner => account number => Account
mapping (address => mapping (uint256 => Account.Storage)) accounts;
// Addresses that can control other users accounts
mapping (address => mapping (address => bool)) operators;
// Addresses that can control all users accounts
mapping (address => bool) globalOperators;
// mutable risk parameters of the system
RiskParams riskParams;
// immutable risk limits of the system
RiskLimits riskLimits;
}
// ============ Functions ============
function getToken(
Storage.State storage state,
uint256 marketId
)
internal
view
returns (address)
{
return state.markets[marketId].token;
}
function getTotalPar(
Storage.State storage state,
uint256 marketId
)
internal
view
returns (Types.TotalPar memory)
{
return state.markets[marketId].totalPar;
}
function getIndex(
Storage.State storage state,
uint256 marketId
)
internal
view
returns (Interest.Index memory)
{
return state.markets[marketId].index;
}
function getNumExcessTokens(
Storage.State storage state,
uint256 marketId
)
internal
view
returns (Types.Wei memory)
{
Interest.Index memory index = state.getIndex(marketId);
Types.TotalPar memory totalPar = state.getTotalPar(marketId);
address token = state.getToken(marketId);
Types.Wei memory balanceWei = Types.Wei({
sign: true,
value: IERC20Detailed(token).balanceOf(address(this))
});
(
Types.Wei memory supplyWei,
Types.Wei memory borrowWei
) = Interest.totalParToWei(totalPar, index);
// borrowWei is negative, so subtracting it makes the value more positive
return balanceWei.sub(borrowWei).sub(supplyWei);
}
function getStatus(
Storage.State storage state,
Account.Info memory account
)
internal
view
returns (Account.Status)
{
return state.accounts[account.owner][account.number].status;
}
function getPar(
Storage.State storage state,
Account.Info memory account,
uint256 marketId
)
internal
view
returns (Types.Par memory)
{
return state.accounts[account.owner][account.number].balances[marketId];
}
function getWei(
Storage.State storage state,
Account.Info memory account,
uint256 marketId
)
internal
view
returns (Types.Wei memory)
{
Types.Par memory par = state.getPar(account, marketId);
if (par.isZero()) {
return Types.zeroWei();
}
Interest.Index memory index = state.getIndex(marketId);
return Interest.parToWei(par, index);
}
function getMarketsWithBalancesSet(
Storage.State storage state,
Account.Info memory account
)
internal
view
returns (EnumerableSet.Set storage)
{
return state.accounts[account.owner][account.number].marketsWithNonZeroBalanceSet;
}
function getMarketsWithBalances(
Storage.State storage state,
Account.Info memory account
)
internal
view
returns (uint256[] memory)
{
return state.accounts[account.owner][account.number].marketsWithNonZeroBalanceSet.values();
}
function getNumberOfMarketsWithBorrow(
Storage.State storage state,
Account.Info memory account
)
internal
view
returns (uint256)
{
return state.accounts[account.owner][account.number].numberOfMarketsWithBorrow;
}
function getLiquidationSpreadForPair(
Storage.State storage state,
uint256 heldMarketId,
uint256 owedMarketId
)
internal
view
returns (Decimal.D256 memory)
{
uint256 result = state.riskParams.liquidationSpread.value;
result = Decimal.mul(result, Decimal.onePlus(state.markets[heldMarketId].spreadPremium));
result = Decimal.mul(result, Decimal.onePlus(state.markets[owedMarketId].spreadPremium));
return Decimal.D256({
value: result
});
}
function fetchNewIndex(
Storage.State storage state,
uint256 marketId,
Interest.Index memory index
)
internal
view
returns (Interest.Index memory)
{
Interest.Rate memory rate = state.fetchInterestRate(marketId, index);
return Interest.calculateNewIndex(
index,
rate,
state.getTotalPar(marketId),
state.riskParams.earningsRate
);
}
function fetchInterestRate(
Storage.State storage state,
uint256 marketId,
Interest.Index memory index
)
internal
view
returns (Interest.Rate memory)
{
Types.TotalPar memory totalPar = state.getTotalPar(marketId);
(
Types.Wei memory supplyWei,
Types.Wei memory borrowWei
) = Interest.totalParToWei(totalPar, index);
Interest.Rate memory rate = state.markets[marketId].interestSetter.getInterestRate(
state.getToken(marketId),
borrowWei.value,
supplyWei.value
);
return rate;
}
function fetchPrice(
Storage.State storage state,
uint256 marketId,
address token
)
internal
view
returns (Monetary.Price memory)
{
IPriceOracle oracle = IPriceOracle(state.markets[marketId].priceOracle);
Monetary.Price memory price = oracle.getPrice(token);
Require.that(
price.value != 0,
FILE,
"Price cannot be zero",
marketId
);
return price;
}
function getAccountValues(
Storage.State storage state,
Account.Info memory account,
Cache.MarketCache memory cache,
bool adjustForLiquidity
)
internal
view
returns (Monetary.Value memory, Monetary.Value memory)
{
Monetary.Value memory supplyValue;
Monetary.Value memory borrowValue;
uint256 numMarkets = cache.getNumMarkets();
for (uint256 i = 0; i < numMarkets; i++) {
Types.Wei memory userWei = state.getWei(account, cache.getAtIndex(i).marketId);
if (userWei.isZero()) {
continue;
}
uint256 assetValue = userWei.value.mul(cache.getAtIndex(i).price.value);
Decimal.D256 memory adjust = Decimal.one();
if (adjustForLiquidity) {
adjust = Decimal.onePlus(state.markets[cache.getAtIndex(i).marketId].marginPremium);
}
if (userWei.sign) {
supplyValue.value = supplyValue.value.add(Decimal.div(assetValue, adjust));
} else {
borrowValue.value = borrowValue.value.add(Decimal.mul(assetValue, adjust));
}
}
return (supplyValue, borrowValue);
}
function isCollateralized(
Storage.State storage state,
Account.Info memory account,
Cache.MarketCache memory cache,
bool requireMinBorrow
)
internal
view
returns (bool)
{
if (state.getNumberOfMarketsWithBorrow(account) == 0) {
// The user does not have a balance with a borrow amount, so they must be collateralized
return true;
}
// get account values (adjusted for liquidity)
(
Monetary.Value memory supplyValue,
Monetary.Value memory borrowValue
) = state.getAccountValues(account, cache, /* adjustForLiquidity = */ true);
if (borrowValue.value == 0) {
return true;
}
if (requireMinBorrow) {
Require.that(
borrowValue.value >= state.riskParams.minBorrowedValue.value,
FILE,
"Borrow value too low",
account.owner,
account.number
);
}
uint256 requiredMargin = Decimal.mul(borrowValue.value, state.riskParams.marginRatio);
return supplyValue.value >= borrowValue.value.add(requiredMargin);
}
function isGlobalOperator(
Storage.State storage state,
address operator
)
internal
view
returns (bool)
{
return state.globalOperators[operator];
}
function isLocalOperator(
Storage.State storage state,
address owner,
address operator
)
internal
view
returns (bool)
{
return state.operators[owner][operator];
}
function requireIsGlobalOperator(
Storage.State storage state,
address operator
)
internal
view
{
bool isValidOperator = state.isGlobalOperator(operator);
Require.that(
isValidOperator,
FILE,
"Unpermissioned global operator",
operator
);
}
function requireIsOperator(
Storage.State storage state,
Account.Info memory account,
address operator
)
internal
view
{
bool isValidOperator =
operator == account.owner
|| state.isGlobalOperator(operator)
|| state.isLocalOperator(account.owner, operator);
Require.that(
isValidOperator,
FILE,
"Unpermissioned operator",
operator
);
}
/**
* Determine and set an account's balance based on the intended balance change. Return the
* equivalent amount in wei
*/
function getNewParAndDeltaWei(
Storage.State storage state,
Account.Info memory account,
uint256 marketId,
Types.AssetAmount memory amount
)
internal
view
returns (Types.Par memory, Types.Wei memory)
{
Types.Par memory oldPar = state.getPar(account, marketId);
if (amount.value == 0 && amount.ref == Types.AssetReference.Delta) {
return (oldPar, Types.zeroWei());
}
Interest.Index memory index = state.getIndex(marketId);
Types.Wei memory oldWei = Interest.parToWei(oldPar, index);
Types.Par memory newPar;
Types.Wei memory deltaWei;
if (amount.denomination == Types.AssetDenomination.Wei) {
deltaWei = Types.Wei({
sign: amount.sign,
value: amount.value
});
if (amount.ref == Types.AssetReference.Target) {
deltaWei = deltaWei.sub(oldWei);
}
newPar = Interest.weiToPar(oldWei.add(deltaWei), index);
} else { // AssetDenomination.Par
newPar = Types.Par({
sign: amount.sign,
value: amount.value.to128()
});
if (amount.ref == Types.AssetReference.Delta) {
newPar = oldPar.add(newPar);
}
deltaWei = Interest.parToWei(newPar, index).sub(oldWei);
}
return (newPar, deltaWei);
}
function getNewParAndDeltaWeiForLiquidation(
Storage.State storage state,
Account.Info memory account,
uint256 marketId,
Types.AssetAmount memory amount
)
internal
view
returns (Types.Par memory, Types.Wei memory)
{
Types.Par memory oldPar = state.getPar(account, marketId);
Require.that(
!oldPar.isPositive(),
FILE,
"Owed balance cannot be positive",
account.owner,
account.number
);
(
Types.Par memory newPar,
Types.Wei memory deltaWei
) = state.getNewParAndDeltaWei(
account,
marketId,
amount
);
// if attempting to over-repay the owed asset, bound it by the maximum
if (newPar.isPositive()) {
newPar = Types.zeroPar();
deltaWei = state.getWei(account, marketId).negative();
}
Require.that(
!deltaWei.isNegative() && oldPar.value >= newPar.value,
FILE,
"Owed balance cannot increase",
account.owner,
account.number
);
// if not paying back enough wei to repay any par, then bound wei to zero
if (oldPar.equals(newPar)) {
deltaWei = Types.zeroWei();
}
return (newPar, deltaWei);
}
function isVaporizable(
Storage.State storage state,
Account.Info memory account,
Cache.MarketCache memory cache
)
internal
view
returns (bool)
{
bool hasNegative = false;
uint256 numMarkets = cache.getNumMarkets();
for (uint256 i = 0; i < numMarkets; i++) {
Types.Par memory par = state.getPar(account, cache.getAtIndex(i).marketId);
if (par.isZero()) {
continue;
} else if (par.sign) {
return false;
} else {
hasNegative = true;
}
}
return hasNegative;
}
// =============== Setter Functions ===============
function updateIndex(
Storage.State storage state,
uint256 marketId
)
internal
returns (Interest.Index memory)
{
Interest.Index memory index = state.getIndex(marketId);
if (index.lastUpdate == Time.currentTime()) {
return index;
}
return state.markets[marketId].index = state.fetchNewIndex(marketId, index);
}
function setStatus(
Storage.State storage state,
Account.Info memory account,
Account.Status status
)
internal
{
state.accounts[account.owner][account.number].status = status;
}
function setPar(
Storage.State storage state,
Account.Info memory account,
uint256 marketId,
Types.Par memory newPar
)
internal
{
Types.Par memory oldPar = state.getPar(account, marketId);
if (Types.equals(oldPar, newPar)) {
// GUARD statement
return;
}
// updateTotalPar
Types.TotalPar memory totalPar = state.getTotalPar(marketId);
// roll-back oldPar
if (oldPar.sign) {
totalPar.supply = uint256(totalPar.supply).sub(oldPar.value).to128();
} else {
totalPar.borrow = uint256(totalPar.borrow).sub(oldPar.value).to128();
}
// roll-forward newPar
if (newPar.sign) {
totalPar.supply = uint256(totalPar.supply).add(newPar.value).to128();
} else {
totalPar.borrow = uint256(totalPar.borrow).add(newPar.value).to128();
}
if (oldPar.isLessThanZero() && newPar.isGreaterThanOrEqualToZero()) {
// user went from borrowing to repaying or positive
state.accounts[account.owner][account.number].numberOfMarketsWithBorrow -= 1;
} else if (oldPar.isGreaterThanOrEqualToZero() && newPar.isLessThanZero()) {
// user went from zero or positive to borrowing
state.accounts[account.owner][account.number].numberOfMarketsWithBorrow += 1;
}
if (newPar.isZero() && (!oldPar.isZero())) {
// User went from a non-zero balance to zero. Remove the market from the set.
state.accounts[account.owner][account.number].marketsWithNonZeroBalanceSet.remove(marketId);
} else if ((!newPar.isZero()) && oldPar.isZero()) {
// User went from zero to non-zero. Add the market to the set.
state.accounts[account.owner][account.number].marketsWithNonZeroBalanceSet.add(marketId);
}
state.markets[marketId].totalPar = totalPar;
state.accounts[account.owner][account.number].balances[marketId] = newPar;
}
/**
* Determine and set an account's balance based on a change in wei
*/
function setParFromDeltaWei(
Storage.State storage state,
Account.Info memory account,
uint256 marketId,
Types.Wei memory deltaWei
)
internal
{
if (deltaWei.isZero()) {
return;
}
Interest.Index memory index = state.getIndex(marketId);
Types.Wei memory oldWei = state.getWei(account, marketId);
Types.Wei memory newWei = oldWei.add(deltaWei);
Types.Par memory newPar = Interest.weiToPar(newWei, index);
state.setPar(
account,
marketId,
newPar
);
}
function initializeCache(
Storage.State storage state,
Cache.MarketCache memory cache
) internal view {
cache.markets = new Cache.MarketInfo[](cache.marketsLength);
uint counter = 0;
// Really neat byproduct of iterating through a bitmap using the least significant bit, where each set flag
// represents the marketId, --> the initialized `cache.markets` array is sorted in O(n)!!!!!!
// Meaning, this function call is O(n) where `n` is the number of markets in the cache
for (uint i = 0; i < cache.marketBitmaps.length; i++) {
uint bitmap = cache.marketBitmaps[i];
while (bitmap != 0) {
uint nextSetBit = Cache.getLeastSignificantBit(bitmap);
uint marketId = (MAX_UINT_BITS * i) + nextSetBit;
address token = state.getToken(marketId);
if (state.markets[marketId].isClosing) {
cache.markets[counter++] = Cache.MarketInfo({
marketId: marketId,
token: token,
isClosing: true,
borrowPar: state.getTotalPar(marketId).borrow,
price: state.fetchPrice(marketId, token)
});
} else {
// don't need the borrowPar if the market is not closing
cache.markets[counter++] = Cache.MarketInfo({
marketId: marketId,
token: token,
isClosing: false,
borrowPar: 0,
price: state.fetchPrice(marketId, token)
});
}
// unset the set bit
bitmap = bitmap - (ONE << nextSetBit);
}
if (counter == cache.marketsLength) {
break;
}
}
Require.that(
cache.marketsLength == counter,
FILE,
"cache initialized improperly",
cache.marketsLength,
cache.markets.length
);
}
}
// File: contracts/protocol/interfaces/IDolomiteMargin.sol
/*
Copyright 2021 Dolomite.
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.5.0;
interface IDolomiteMargin {
// ============ Getters for Markets ============
/**
* Get the ERC20 token address for a market.
*
* @param token The token to query
* @return The token's marketId if the token is valid
*/
function getMarketIdByTokenAddress(
address token
) external view returns (uint256);
/**
* Get the ERC20 token address for a market.
*
* @param marketId The market to query
* @return The token address
*/
function getMarketTokenAddress(
uint256 marketId
) external view returns (address);
/**
* Return true if a particular market is in closing mode. Additional borrows cannot be taken
* from a market that is closing.
*
* @param marketId The market to query
* @return True if the market is closing
*/
function getMarketIsClosing(
uint256 marketId
)
external
view
returns (bool);
/**
* Get the price of the token for a market.
*
* @param marketId The market to query
* @return The price of each atomic unit of the token
*/
function getMarketPrice(
uint256 marketId
) external view returns (Monetary.Price memory);
/**
* Get the total number of markets.
*
* @return The number of markets
*/
function getNumMarkets() external view returns (uint256);
/**
* Get the total principal amounts (borrowed and supplied) for a market.
*
* @param marketId The market to query
* @return The total principal amounts
*/
function getMarketTotalPar(
uint256 marketId
) external view returns (Types.TotalPar memory);
/**
* Get the most recently cached interest index for a market.
*
* @param marketId The market to query
* @return The most recent index
*/
function getMarketCachedIndex(
uint256 marketId
) external view returns (Interest.Index memory);
/**
* Get the interest index for a market if it were to be updated right now.
*
* @param marketId The market to query
* @return The estimated current index
*/
function getMarketCurrentIndex(
uint256 marketId
) external view returns (Interest.Index memory);
/**
* Get the price oracle address for a market.
*
* @param marketId The market to query
* @return The price oracle address
*/
function getMarketPriceOracle(
uint256 marketId
) external view returns (IPriceOracle);
/**
* Get the interest-setter address for a market.
*
* @param marketId The market to query
* @return The interest-setter address
*/
function getMarketInterestSetter(
uint256 marketId
) external view returns (IInterestSetter);
/**
* Get the margin premium for a market. A margin premium makes it so that any positions that
* include the market require a higher collateralization to avoid being liquidated.
*
* @param marketId The market to query
* @return The market's margin premium
*/
function getMarketMarginPremium(
uint256 marketId
) external view returns (Decimal.D256 memory);
/**
* Get the spread premium for a market. A spread premium makes it so that any liquidations
* that include the market have a higher spread than the global default.
*
* @param marketId The market to query
* @return The market's spread premium
*/
function getMarketSpreadPremium(
uint256 marketId
) external view returns (Decimal.D256 memory);
/**
* Return true if this market can be removed and its ID can be recycled and reused
*
* @param marketId The market to query
* @return True if the market is recyclable
*/
function getMarketIsRecyclable(
uint256 marketId
) external view returns (bool);
/**
* Gets the recyclable markets, up to `n` length. If `n` is greater than the length of the list, 0's are returned
* for the empty slots.
*
* @param n The number of markets to get, bounded by the linked list being smaller than `n`
* @return The list of recyclable markets, in the same order held by the linked list
*/
function getRecyclableMarkets(
uint256 n
) external view returns (uint[] memory);
/**
* Get the current borrower interest rate for a market.
*
* @param marketId The market to query
* @return The current interest rate
*/
function getMarketInterestRate(
uint256 marketId
) external view returns (Interest.Rate memory);
/**
* Get basic information about a particular market.
*
* @param marketId The market to query
* @return A Storage.Market struct with the current state of the market
*/
function getMarket(
uint256 marketId
) external view returns (Storage.Market memory);
/**
* Get comprehensive information about a particular market.
*
* @param marketId The market to query
* @return A tuple containing the values:
* - A Storage.Market struct with the current state of the market
* - The current estimated interest index
* - The current token price
* - The current market interest rate
*/
function getMarketWithInfo(
uint256 marketId
)
external
view
returns (
Storage.Market memory,
Interest.Index memory,
Monetary.Price memory,
Interest.Rate memory
);
/**
* Get the number of excess tokens for a market. The number of excess tokens is calculated by taking the current
* number of tokens held in DolomiteMargin, adding the number of tokens owed to DolomiteMargin by borrowers, and
* subtracting the number of tokens owed to suppliers by DolomiteMargin.
*
* @param marketId The market to query
* @return The number of excess tokens
*/
function getNumExcessTokens(
uint256 marketId
) external view returns (Types.Wei memory);
// ============ Getters for Accounts ============
/**
* Get the principal value for a particular account and market.
*
* @param account The account to query
* @param marketId The market to query
* @return The principal value
*/
function getAccountPar(
Account.Info calldata account,
uint256 marketId
) external view returns (Types.Par memory);
/**
* Get the principal value for a particular account and market, with no check the market is valid. Meaning, markets
* that don't exist return 0.
*
* @param account The account to query
* @param marketId The market to query
* @return The principal value
*/
function getAccountParNoMarketCheck(
Account.Info calldata account,
uint256 marketId
) external view returns (Types.Par memory);
/**
* Get the token balance for a particular account and market.
*
* @param account The account to query
* @param marketId The market to query
* @return The token amount
*/
function getAccountWei(
Account.Info calldata account,
uint256 marketId
) external view returns (Types.Wei memory);
/**
* Get the status of an account (Normal, Liquidating, or Vaporizing).
*
* @param account The account to query
* @return The account's status
*/
function getAccountStatus(
Account.Info calldata account
) external view returns (Account.Status);
/**
* Get a list of markets that have a non-zero balance for an account
*
* @param account The account to query
* @return The non-sorted marketIds with non-zero balance for the account.
*/
function getAccountMarketsWithNonZeroBalances(
Account.Info calldata account
) external view returns (uint256[] memory);
/**
* Get the number of markets with which an account has a negative balance.
*
* @param account The account to query
* @return The non-sorted marketIds with non-zero balance for the account.
*/
function getNumberOfMarketsWithBorrow(
Account.Info calldata account
) external view returns (uint256);
/**
* Get the total supplied and total borrowed value of an account.
*
* @param account The account to query
* @return The following values:
* - The supplied value of the account
* - The borrowed value of the account
*/
function getAccountValues(
Account.Info calldata account
) external view returns (Monetary.Value memory, Monetary.Value memory);
/**
* Get the total supplied and total borrowed values of an account adjusted by the marginPremium
* of each market. Supplied values are divided by (1 + marginPremium) for each market and
* borrowed values are multiplied by (1 + marginPremium) for each market. Comparing these
* adjusted values gives the margin-ratio of the account which will be compared to the global
* margin-ratio when determining if the account can be liquidated.
*
* @param account The account to query
* @return The following values:
* - The supplied value of the account (adjusted for marginPremium)
* - The borrowed value of the account (adjusted for marginPremium)
*/
function getAdjustedAccountValues(
Account.Info calldata account
) external view returns (Monetary.Value memory, Monetary.Value memory);
/**
* Get an account's summary for each market.
*
* @param account The account to query
* @return The following values:
* - The market IDs for each market
* - The ERC20 token address for each market
* - The account's principal value for each market
* - The account's (supplied or borrowed) number of tokens for each market
*/
function getAccountBalances(
Account.Info calldata account
) external view returns (uint[] memory, address[] memory, Types.Par[] memory, Types.Wei[] memory);
// ============ Getters for Account Permissions ============
/**
* Return true if a particular address is approved as an operator for an owner's accounts.
* Approved operators can act on the accounts of the owner as if it were the operator's own.
*
* @param owner The owner of the accounts
* @param operator The possible operator
* @return True if operator is approved for owner's accounts
*/
function getIsLocalOperator(
address owner,
address operator
) external view returns (bool);
/**
* Return true if a particular address is approved as a global operator. Such an address can
* act on any account as if it were the operator's own.
*
* @param operator The address to query
* @return True if operator is a global operator
*/
function getIsGlobalOperator(
address operator
) external view returns (bool);
// ============ Getters for Risk Params ============
/**
* Get the global minimum margin-ratio that every position must maintain to prevent being
* liquidated.
*
* @return The global margin-ratio
*/
function getMarginRatio() external view returns (Decimal.D256 memory);
/**
* Get the global liquidation spread. This is the spread between oracle prices that incentivizes
* the liquidation of risky positions.
*
* @return The global liquidation spread
*/
function getLiquidationSpread() external view returns (Decimal.D256 memory);
/**
* Get the adjusted liquidation spread for some market pair. This is equal to the global
* liquidation spread multiplied by (1 + spreadPremium) for each of the two markets.
*
* @param heldMarketId The market for which the account has collateral
* @param owedMarketId The market for which the account has borrowed tokens
* @return The adjusted liquidation spread
*/
function getLiquidationSpreadForPair(
uint256 heldMarketId,
uint256 owedMarketId
) external view returns (Decimal.D256 memory);
/**
* Get the global earnings-rate variable that determines what percentage of the interest paid
* by borrowers gets passed-on to suppliers.
*
* @return The global earnings rate
*/
function getEarningsRate() external view returns (Decimal.D256 memory);
/**
* Get the global minimum-borrow value which is the minimum value of any new borrow on DolomiteMargin.
*
* @return The global minimum borrow value
*/
function getMinBorrowedValue() external view returns (Monetary.Value memory);
/**
* Get all risk parameters in a single struct.
*
* @return All global risk parameters
*/
function getRiskParams() external view returns (Storage.RiskParams memory);
/**
* Get all risk parameter limits in a single struct. These are the maximum limits at which the
* risk parameters can be set by the admin of DolomiteMargin.
*
* @return All global risk parameter limits
*/
function getRiskLimits() external view returns (Storage.RiskLimits memory);
// ============ Write Functions ============
/**
* The main entry-point to DolomiteMargin that allows users and contracts to manage accounts.
* Take one or more actions on one or more accounts. The msg.sender must be the owner or
* operator of all accounts except for those being liquidated, vaporized, or traded with.
* One call to operate() is considered a singular "operation". Account collateralization is
* ensured only after the completion of the entire operation.
*
* @param accounts A list of all accounts that will be used in this operation. Cannot contain
* duplicates. In each action, the relevant account will be referred-to by its
* index in the list.
* @param actions An ordered list of all actions that will be taken in this operation. The
* actions will be processed in order.
*/
function operate(
Account.Info[] calldata accounts,
Actions.ActionArgs[] calldata actions
) external;
/**
* Approves/disapproves any number of operators. An operator is an external address that has the
* same permissions to manipulate an account as the owner of the account. Operators are simply
* addresses and therefore may either be externally-owned Ethereum accounts OR smart contracts.
*
* Operators are also able to act as AutoTrader contracts on behalf of the account owner if the
* operator is a smart contract and implements the IAutoTrader interface.
*
* @param args A list of OperatorArgs which have an address and a boolean. The boolean value
* denotes whether to approve (true) or revoke approval (false) for that address.
*/
function setOperators(
Types.OperatorArg[] calldata args
) external;
}
// File: contracts/external/helpers/OnlyDolomiteMargin.sol
/*
Copyright 2019 dYdX Trading 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.5.7;
/**
* @title onlyDolomiteMargin
* @author dYdX
*
* Inheritable contract that restricts the calling of certain functions to DolomiteMargin only
*/
contract OnlyDolomiteMargin {
// ============ Constants ============
bytes32 constant FILE = "OnlyDolomiteMargin";
// ============ Storage ============
IDolomiteMargin public DOLOMITE_MARGIN;
// ============ Constructor ============
constructor (
address dolomiteMargin
)
public
{
DOLOMITE_MARGIN = IDolomiteMargin(dolomiteMargin);
}
// ============ Modifiers ============
modifier onlyDolomiteMargin(address from) {
Require.that(
from == address(DOLOMITE_MARGIN),
FILE,
"Only Dolomite can call function",
from
);
_;
}
}
// File: contracts/external/proxies/PayableProxy.sol
/*
Copyright 2019 dYdX Trading 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.5.7;
/**
* @title PayableProxy
* @author dYdX
*
* Contract for wrapping/unwrapping ETH before/after interacting with DolomiteMargin
*/
contract PayableProxy is OnlyDolomiteMargin, ReentrancyGuard {
// ============ Constants ============
bytes32 constant FILE = "PayableProxy";
// ============ Storage ============
WETH9 public WETH;
// ============ Constructor ============
constructor (
address dolomiteMargin,
address payable weth
)
public
OnlyDolomiteMargin(dolomiteMargin)
{
WETH = WETH9(weth);
WETH.approve(dolomiteMargin, uint256(-1));
}
// ============ Public Functions ============
/**
* Fallback function. Disallows ether to be sent to this contract without data except when
* unwrapping WETH.
*/
function ()
external
payable
{
require( // coverage-disable-line
msg.sender == address(WETH),
"Cannot receive ETH"
);
}
function operate(
Account.Info[] memory accounts,
Actions.ActionArgs[] memory actions,
address payable sendEthTo
)
public
payable
nonReentrant
{
WETH9 weth = WETH;
// create WETH from ETH
if (msg.value != 0) {
weth.deposit.value(msg.value)();
}
// validate the input
for (uint256 i = 0; i < actions.length; i++) {
Actions.ActionArgs memory action = actions[i];
// Can only operate on accounts owned by msg.sender
address owner1 = accounts[action.accountId].owner;
Require.that(
owner1 == msg.sender,
FILE,
"Sender must be primary account",
owner1
);
// For a transfer both accounts must be owned by msg.sender
if (action.actionType == Actions.ActionType.Transfer) {
address owner2 = accounts[action.otherAccountId].owner;
Require.that(
owner2 == msg.sender,
FILE,
"Sender must be secondary account",
owner2
);
}
}
DOLOMITE_MARGIN.operate(accounts, actions);
// return all remaining WETH to the sendEthTo as ETH
uint256 remainingWeth = weth.balanceOf(address(this));
if (remainingWeth != 0) {
Require.that(
sendEthTo != address(0),
FILE,
"Must set sendEthTo"
);
weth.withdraw(remainingWeth);
sendEthTo.transfer(remainingWeth);
}
}
}
| GUARD statement roll-back oldPar roll-forward newPar user went from borrowing to repaying or positive user went from zero or positive to borrowing User went from a non-zero balance to zero. Remove the market from the set. User went from zero to non-zero. Add the market to the set. | function setPar(
Storage.State storage state,
Account.Info memory account,
uint256 marketId,
Types.Par memory newPar
)
internal
{
Types.Par memory oldPar = state.getPar(account, marketId);
if (Types.equals(oldPar, newPar)) {
return;
}
if (oldPar.sign) {
totalPar.supply = uint256(totalPar.supply).sub(oldPar.value).to128();
totalPar.borrow = uint256(totalPar.borrow).sub(oldPar.value).to128();
}
if (newPar.sign) {
totalPar.supply = uint256(totalPar.supply).add(newPar.value).to128();
totalPar.borrow = uint256(totalPar.borrow).add(newPar.value).to128();
}
if (oldPar.isLessThanZero() && newPar.isGreaterThanOrEqualToZero()) {
state.accounts[account.owner][account.number].numberOfMarketsWithBorrow -= 1;
state.accounts[account.owner][account.number].numberOfMarketsWithBorrow += 1;
}
if (newPar.isZero() && (!oldPar.isZero())) {
state.accounts[account.owner][account.number].marketsWithNonZeroBalanceSet.remove(marketId);
state.accounts[account.owner][account.number].marketsWithNonZeroBalanceSet.add(marketId);
}
state.markets[marketId].totalPar = totalPar;
state.accounts[account.owner][account.number].balances[marketId] = newPar;
}
| 6,397,810 |
./partial_match/1/0xE950159CCdF36f6Dc661DEC0E0De75113455bF63/sources/contracts/sh-verify/sETH.sol | Mints a given amount of tokens Only slot settlement registry module can call _recipient of the tokens _amount of tokens to mint | function mint(address _recipient, uint256 _amount) external {
require(msg.sender == address(slotRegistry), "mint: Only SLOT registry");
_mint(_recipient, _amount);
}
| 15,964,474 |
./partial_match/3/0x529242E2680f288460d4be3f7b93F3699bec1d31/sources/NUG.sol | 1342465753424 = ~ 4900000 NUNS_PER_NUG / 365 / | function _waasLobby(uint256 enterDay)
private
returns (uint256 waasLobby)
{
if (enterDay > 0 && enterDay <= 180) {
waasLobby = CLAIM_STARTING_AMOUNT - ((enterDay - 1) * 2222222222222);
waasLobby = CLAIM_LOWEST_AMOUNT;
}
return waasLobby;
}
| 5,293,752 |
pragma solidity ^0.4.2;
// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function approve(address _to, uint256 _tokenId) public;
function balanceOf(address _owner) public view returns (uint256 balance);
function implementsERC721() public pure returns (bool);
function ownerOf(uint256 _tokenId) public view returns (address addr);
function takeOwnership(uint256 _tokenId) public;
function totalSupply() public view returns (uint256 total);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
event Transfer(address indexed from, address indexed to, uint256 tokenId);
event Approval(address indexed owner, address indexed approved, uint256 tokenId);
}
contract Elements is ERC721 {
/*** EVENTS ***/
// @dev The Birth event is fired whenever a new element comes into existence.
event Birth(uint256 tokenId, string name, address owner);
// @dev The TokenSold event is fired whenever a token is sold.
event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name);
// @dev Transfer event as defined in current draft of ERC721. Ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
/*** CONSTANTS, VARIABLES ***/
// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant NAME = "CryptoElements"; // solhint-disable-line
string public constant SYMBOL = "CREL"; // solhint-disable-line
uint256 private periodicStartingPrice = 5 ether;
uint256 private elementStartingPrice = 0.005 ether;
uint256 private scientistStartingPrice = 0.1 ether;
uint256 private specialStartingPrice = 0.05 ether;
uint256 private firstStepLimit = 0.05 ether;
uint256 private secondStepLimit = 0.75 ether;
uint256 private thirdStepLimit = 3 ether;
bool private periodicTableExists = false;
uint256 private elementCTR = 0;
uint256 private scientistCTR = 0;
uint256 private specialCTR = 0;
uint256 private constant elementSTART = 1;
uint256 private constant scientistSTART = 1000;
uint256 private constant specialSTART = 10000;
uint256 private constant specialLIMIT = 5000;
/*** STORAGE ***/
// @dev A mapping from element IDs to the address that owns them. All elements have
// some valid owner address.
mapping (uint256 => address) public elementIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) private ownershipTokenCount;
// @dev A mapping from ElementIDs to an address that has been approved to call
// transferFrom(). Each Element can only have one approved address for transfer
// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public elementIndexToApproved;
// @dev A mapping from ElementIDs to the price of the token.
mapping (uint256 => uint256) private elementIndexToPrice;
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cooAddress;
/*** DATATYPES ***/
struct Element {
uint256 tokenId;
string name;
uint256 scientistId;
}
mapping(uint256 => Element) elements;
uint256[] tokens;
/*** ACCESS MODIFIERS ***/
// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
// Access modifier for contract owner only functionality
modifier onlyCLevel() {
require(
msg.sender == ceoAddress ||
msg.sender == cooAddress
);
_;
}
/*** CONSTRUCTOR ***/
function Elements() public {
ceoAddress = msg.sender;
cooAddress = msg.sender;
createContractPeriodicTable("Periodic");
}
/*** PUBLIC FUNCTIONS ***/
// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom().
// @param _to The address to be granted transfer approval. Pass address(0) to
// clear all approvals.
// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
// @dev Required for ERC-721 compliance.
function approve(address _to, uint256 _tokenId) public {
// Caller must own token.
require(_owns(msg.sender, _tokenId));
elementIndexToApproved[_tokenId] = _to;
Approval(msg.sender, _to, _tokenId);
}
// For querying balance of a particular account
// @param _owner The address for balance query
// @dev Required for ERC-721 compliance.
function balanceOf(address _owner) public view returns (uint256 balance) {
return ownershipTokenCount[_owner];
}
// @notice Returns all the relevant information about a specific element.
// @param _tokenId The tokenId of the element of interest.
function getElement(uint256 _tokenId) public view returns (
uint256 tokenId,
string elementName,
uint256 sellingPrice,
address owner,
uint256 scientistId
) {
Element storage element = elements[_tokenId];
tokenId = element.tokenId;
elementName = element.name;
sellingPrice = elementIndexToPrice[_tokenId];
owner = elementIndexToOwner[_tokenId];
scientistId = element.scientistId;
}
function implementsERC721() public pure returns (bool) {
return true;
}
// For querying owner of token
// @param _tokenId The tokenID for owner inquiry
// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId) public view returns (address owner) {
owner = elementIndexToOwner[_tokenId];
require(owner != address(0));
}
function payout(address _to) public onlyCLevel {
_payout(_to);
}
// Allows someone to send ether and obtain the token
function purchase(uint256 _tokenId) public payable {
address oldOwner = elementIndexToOwner[_tokenId];
address newOwner = msg.sender;
uint256 sellingPrice = elementIndexToPrice[_tokenId];
// Making sure token owner is not sending to self
require(oldOwner != newOwner);
require(sellingPrice > 0);
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure sent amount is greater than or equal to the sellingPrice
require(msg.value >= sellingPrice);
uint256 ownerPayout = SafeMath.mul(SafeMath.div(sellingPrice, 100), 96);
uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice);
uint256 feeOnce = SafeMath.div(SafeMath.sub(sellingPrice, ownerPayout), 4);
uint256 fee_for_dev = SafeMath.mul(feeOnce, 2);
// Pay previous tokenOwner if owner is not contract
// and if previous price is not 0
if (oldOwner != address(this)) {
// old owner gets entire initial payment back
oldOwner.transfer(ownerPayout);
} else {
fee_for_dev = SafeMath.add(fee_for_dev, ownerPayout);
}
// Taxes for Periodic Table owner
if (elementIndexToOwner[0] != address(this)) {
elementIndexToOwner[0].transfer(feeOnce);
} else {
fee_for_dev = SafeMath.add(fee_for_dev, feeOnce);
}
// Taxes for Scientist Owner for given Element
uint256 scientistId = elements[_tokenId].scientistId;
if ( scientistId != scientistSTART ) {
if (elementIndexToOwner[scientistId] != address(this)) {
elementIndexToOwner[scientistId].transfer(feeOnce);
} else {
fee_for_dev = SafeMath.add(fee_for_dev, feeOnce);
}
} else {
fee_for_dev = SafeMath.add(fee_for_dev, feeOnce);
}
if (purchaseExcess > 0) {
msg.sender.transfer(purchaseExcess);
}
ceoAddress.transfer(fee_for_dev);
_transfer(oldOwner, newOwner, _tokenId);
//TokenSold(_tokenId, sellingPrice, elementIndexToPrice[_tokenId], oldOwner, newOwner, elements[_tokenId].name);
// Update prices
if (sellingPrice < firstStepLimit) {
// first stage
elementIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 100);
} else if (sellingPrice < secondStepLimit) {
// second stage
elementIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 150), 100);
} else if (sellingPrice < thirdStepLimit) {
// third stage
elementIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 130), 100);
} else {
// fourth stage
elementIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 100);
}
}
function priceOf(uint256 _tokenId) public view returns (uint256 price) {
return elementIndexToPrice[_tokenId];
}
// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
// @dev Assigns a new address to act as the COO. Only available to the current COO.
// @param _newCOO The address of the new COO
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
// @notice Allow pre-approved user to take ownership of a token
// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
// @dev Required for ERC-721 compliance.
function takeOwnership(uint256 _tokenId) public {
address newOwner = msg.sender;
address oldOwner = elementIndexToOwner[_tokenId];
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure transfer is approved
require(_approved(newOwner, _tokenId));
_transfer(oldOwner, newOwner, _tokenId);
}
// @param _owner The owner whose element tokens we are interested in.
// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
// expensive (it walks the entire Elements array looking for elements belonging to owner),
// but it also returns a dynamic array, which is only supported for web3 calls, and
// not contract-to-contract calls.
function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalElements = totalSupply();
uint256 resultIndex = 0;
uint256 elementId;
for (elementId = 0; elementId < totalElements; elementId++) {
uint256 tokenId = tokens[elementId];
if (elementIndexToOwner[tokenId] == _owner) {
result[resultIndex] = tokenId;
resultIndex++;
}
}
return result;
}
}
// For querying totalSupply of token
// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint256 total) {
return tokens.length;
}
// Owner initates the transfer of the token to another account
// @param _to The address for the token to be transferred to.
// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
// @dev Required for ERC-721 compliance.
function transfer( address _to, uint256 _tokenId ) public {
require(_owns(msg.sender, _tokenId));
require(_addressNotNull(_to));
_transfer(msg.sender, _to, _tokenId);
}
// Third-party initiates transfer of token from address _from to address _to
// @param _from The address for the token to be transferred from.
// @param _to The address for the token to be transferred to.
// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
// @dev Required for ERC-721 compliance.
function transferFrom( address _from, address _to, uint256 _tokenId) public {
require(_owns(_from, _tokenId));
require(_approved(_to, _tokenId));
require(_addressNotNull(_to));
_transfer(_from, _to, _tokenId);
}
/*** PRIVATE FUNCTIONS ***/
// Safety check on _to address to prevent against an unexpected 0x0 default.
function _addressNotNull(address _to) private pure returns (bool) {
return _to != address(0);
}
// For checking approval of transfer for address _to
function _approved(address _to, uint256 _tokenId) private view returns (bool) {
return elementIndexToApproved[_tokenId] == _to;
}
// Private method for creating Element
function _createElement(uint256 _id, string _name, address _owner, uint256 _price, uint256 _scientistId) private returns (string) {
uint256 newElementId = _id;
// It's probably never going to happen, 4 billion tokens are A LOT, but
// let's just be 100% sure we never let this happen.
require(newElementId == uint256(uint32(newElementId)));
elements[_id] = Element(_id, _name, _scientistId);
Birth(newElementId, _name, _owner);
elementIndexToPrice[newElementId] = _price;
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(address(0), _owner, newElementId);
tokens.push(_id);
return _name;
}
// @dev Creates Periodic Table as first element
function createContractPeriodicTable(string _name) public onlyCEO {
require(periodicTableExists == false);
_createElement(0, _name, address(this), periodicStartingPrice, scientistSTART);
periodicTableExists = true;
}
// @dev Creates a new Element with the given name and Id
function createContractElement(string _name, uint256 _scientistId) public onlyCEO {
require(periodicTableExists == true);
uint256 _id = SafeMath.add(elementCTR, elementSTART);
uint256 _scientistIdProcessed = SafeMath.add(_scientistId, scientistSTART);
_createElement(_id, _name, address(this), elementStartingPrice, _scientistIdProcessed);
elementCTR = SafeMath.add(elementCTR, 1);
}
// @dev Creates a new Scientist with the given name Id
function createContractScientist(string _name) public onlyCEO {
require(periodicTableExists == true);
// to start from 1001
scientistCTR = SafeMath.add(scientistCTR, 1);
uint256 _id = SafeMath.add(scientistCTR, scientistSTART);
_createElement(_id, _name, address(this), scientistStartingPrice, scientistSTART);
}
// @dev Creates a new Special Card with the given name Id
function createContractSpecial(string _name) public onlyCEO {
require(periodicTableExists == true);
require(specialCTR <= specialLIMIT);
// to start from 10001
specialCTR = SafeMath.add(specialCTR, 1);
uint256 _id = SafeMath.add(specialCTR, specialSTART);
_createElement(_id, _name, address(this), specialStartingPrice, scientistSTART);
}
// Check for token ownership
function _owns(address claimant, uint256 _tokenId) private view returns (bool) {
return claimant == elementIndexToOwner[_tokenId];
}
//**** HELPERS for checking elements, scientists and special cards
function checkPeriodic() public view returns (bool) {
return periodicTableExists;
}
function getTotalElements() public view returns (uint256) {
return elementCTR;
}
function getTotalScientists() public view returns (uint256) {
return scientistCTR;
}
function getTotalSpecials() public view returns (uint256) {
return specialCTR;
}
//**** HELPERS for changing prices limits and steps if it would be bad, community would like different
function changeStartingPricesLimits(uint256 _elementStartPrice, uint256 _scientistStartPrice, uint256 _specialStartPrice) public onlyCEO {
elementStartingPrice = _elementStartPrice;
scientistStartingPrice = _scientistStartPrice;
specialStartingPrice = _specialStartPrice;
}
function changeStepPricesLimits(uint256 _first, uint256 _second, uint256 _third) public onlyCEO {
firstStepLimit = _first;
secondStepLimit = _second;
thirdStepLimit = _third;
}
// in case of error when assigning scientist to given element
function changeScientistForElement(uint256 _tokenId, uint256 _scientistId) public onlyCEO {
Element storage element = elements[_tokenId];
element.scientistId = SafeMath.add(_scientistId, scientistSTART);
}
function changeElementName(uint256 _tokenId, string _name) public onlyCEO {
Element storage element = elements[_tokenId];
element.name = _name;
}
// This function can be used by the owner of a token to modify the current price
function modifyTokenPrice(uint256 _tokenId, uint256 _newPrice) public payable {
require(_newPrice > elementStartingPrice);
require(elementIndexToOwner[_tokenId] == msg.sender);
require(_newPrice < elementIndexToPrice[_tokenId]);
if ( _tokenId == 0) {
require(_newPrice > periodicStartingPrice);
} else if ( _tokenId < 1000) {
require(_newPrice > elementStartingPrice);
} else if ( _tokenId < 10000 ) {
require(_newPrice > scientistStartingPrice);
} else {
require(_newPrice > specialStartingPrice);
}
elementIndexToPrice[_tokenId] = _newPrice;
}
// For paying out balance on contract
function _payout(address _to) private {
if (_to == address(0)) {
ceoAddress.transfer(this.balance);
} else {
_to.transfer(this.balance);
}
}
// @dev Assigns ownership of a specific Element to an address.
function _transfer(address _from, address _to, uint256 _tokenId) private {
// Since the number of elements is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
//transfer ownership
elementIndexToOwner[_tokenId] = _to;
// When creating new elements _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete elementIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
}
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;
}
} | _owner The owner whose element tokens we are interested in. This method MUST NEVER be called by smart contract code. First, it's fairly expensive (it walks the entire Elements array looking for elements belonging to owner), but it also returns a dynamic array, which is only supported for web3 calls, and not contract-to-contract calls. Return an empty array | function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
uint256[] memory result = new uint256[](tokenCount);
uint256 totalElements = totalSupply();
uint256 resultIndex = 0;
uint256 elementId;
for (elementId = 0; elementId < totalElements; elementId++) {
uint256 tokenId = tokens[elementId];
if (elementIndexToOwner[tokenId] == _owner) {
result[resultIndex] = tokenId;
resultIndex++;
}
}
return result;
}
}
| 5,503,528 |
./full_match/42/0x9978Bc141d6fb9E9b3E0E63EfEAaa359c8355081/sources/contracts/FController.sol | Set the given borrow caps for the given rToken markets. Borrowing that brings total borrows to or above borrow cap will revert. Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. rTokens The addresses of the markets (tokens) to change the borrow caps for newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing./ | function _setMarketBorrowCaps(FRToken[] calldata rTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps");
uint numMarkets = rTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for(uint i = 0; i < numMarkets; i++) {
borrowCaps[address(rTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(rTokens[i], newBorrowCaps[i]);
}
}
| 16,224,494 |
pragma solidity ^0.7.1;
/**
* @title Utilized for ongoing development.
*/
// Open Zeppelin
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
// Internal
import {VaultVenue} from "./VaultVenue.sol";
import {SafeMath} from "../libraries/SafeMath.sol";
import "hardhat/console.sol";
contract BasicVenue is VaultVenue {
using SafeERC20 for IERC20; // Reverts when `transfer` or `transferFrom` erc20 calls don't return proper data
using SafeMath for uint256; // Reverts on math underflows/overflows
// ===== Constructor =====
constructor(
address weth_,
address house_,
address wToken_
) VaultVenue(weth_, house_, wToken_) {}
// ===== Mutable =====
/**
* @notice A basic function to deposit an option into a wrap token, and return it to the _house.
*/
function mintOptionsThenWrap(
bytes32 oid,
uint256 amount,
address receiver
) public returns (bool) {
// Receivers are this address
address[] memory receivers = new address[](2);
receivers[0] = address(this);
receivers[1] = address(this);
console.log("minting options");
// Call the _house to mint options, pulls base tokens to the _house from the executing caller
_mintOptions(oid, amount, receivers, false);
// Get option addresses
(address long, address short) = _house.getOptionTokens(oid);
// Send option tokens to a wrapped token, which is then sent back to the _house.
_wrapOptionForHouse(oid, amount);
return true;
}
// let a venue borrow options. TEST FUNCTION ONLY DO NOT DEPLOY
// todo make specific VenueTest.sol with test utility fns
function borrowOptionTest(
bytes32 oid,
uint256 amount
) public returns (bool) {
// Receivers are this address
address[] memory receivers = new address[](2);
receivers[0] = address(this);
receivers[1] = address(this);
_house.borrowOptions(oid, amount, receivers);
return true;
}
/**
* @notice Exercises the `oid` option using the balance of the long stored in this contract.
*/
function exerciseFromBalance(
bytes32 oid,
uint256 amount,
address receiver
) public {
(address long, ) = _house.getOptionTokens(oid);
uint256 balance = balanceOfUser[_house.getExecutingCaller()][long];
console.log("checking balance in venue", balance, amount);
require(balance >= amount, "Venue: ABOVE_MAX");
// exercise options using the House
console.log("venue._exerciseOptions");
_exerciseOptions(oid, amount, receiver, true);
}
function exerciseFromWrappedBalance(
bytes32 oid,
uint256 amount,
address receiver
) public {
// Receivers are this address
address[] memory receivers = new address[](2);
receivers[0] = address(this);
receivers[1] = address(this);
splitOptionsAndDeposit(oid, amount, receivers);
(address long, ) = _house.getOptionTokens(oid);
uint256 balance = balanceOfUser[_house.getExecutingCaller()][long];
console.log("checking balance in venue", balance, amount);
require(balance >= amount, "Venue: ABOVE_MAX");
// exercise options using the House
console.log("venue._exerciseOptions");
_exerciseOptions(oid, amount, receiver, true);
}
function redeemFromBalance(
bytes32 oid,
uint256 amount,
address receiver
) public {
(, address short) = _house.getOptionTokens(oid);
uint256 balance = balanceOfUser[_house.getExecutingCaller()][short];
console.log("checking balance in venue", balance, amount);
require(balance >= amount, "Venue: ABOVE_MAX");
// exercise options using the House
console.log("venue._exerciseOptions");
_redeemOptions(oid, amount, receiver, true);
}
function closeFromWrappedBalance(
bytes32 oid,
uint256 amount,
address receiver
) public {
// Receivers are this address
address[] memory receivers = new address[](2);
receivers[0] = address(this);
receivers[1] = address(this);
splitOptionsAndDeposit(oid, amount, receivers);
(address long, ) = _house.getOptionTokens(oid);
uint256 balance = balanceOfUser[_house.getExecutingCaller()][long];
console.log("checking balance in venue", balance, amount);
require(balance >= amount, "Venue: ABOVE_MAX");
// exercise options using the House
console.log("venue._exerciseOptions");
_closeOptions(oid, amount, receiver, true);
}
function closeFromBalance(
bytes32 oid,
uint256 amount,
address receiver
) public {
(address long, ) = _house.getOptionTokens(oid);
uint256 balance = balanceOfUser[_house.getExecutingCaller()][long];
console.log("checking balance in venue", balance, amount);
require(balance >= amount, "Venue: ABOVE_MAX");
// exercise options using the House
console.log("venue._closeOptions");
_closeOptions(oid, amount, receiver, true);
}
function close(
bytes32 oid,
uint256 amount,
address receiver
) public {
(address long, ) = _house.getOptionTokens(oid);
uint256 balance = balanceOfUser[_house.getExecutingCaller()][long];
console.log("checking balance in venue", balance, amount);
require(balance >= amount, "Venue: ABOVE_MAX");
// exercise options using the House
console.log("venue._closeOptions");
_closeOptions(oid, amount, receiver, false);
}
// ===== Test =====
uint256 private _test;
function getTest() public view returns (uint256) {
return _test;
}
event SetTest(uint256 value);
function setTest(uint256 value) public {
_test = value;
emit SetTest(value);
}
// ===== View =====
}
| let a venue borrow options. TEST FUNCTION ONLY DO NOT DEPLOY todo make specific VenueTest.sol with test utility fns Receivers are this address | function borrowOptionTest(
bytes32 oid,
uint256 amount
) public returns (bool) {
address[] memory receivers = new address[](2);
receivers[0] = address(this);
receivers[1] = address(this);
_house.borrowOptions(oid, amount, receivers);
return true;
}
| 12,553,344 |
./full_match/1/0x51e63665AC51D0313A042d89DEd26763936C0D12/sources/contracts/NeozenMythics.sol | Check if mint is live | function isLive() public view returns (bool) {
return block.timestamp >= liveAt && block.timestamp <= expiresAt;
}
| 8,329,497 |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, 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 unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 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 unsigned integers, 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 unsigned integers, 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 unsigned integers 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;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* Owned contract
*/
contract Owned {
address payable public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address payable _newOwner) public onlyOwner {
owner = _newOwner;
emit OwnershipTransferred(msg.sender, _newOwner);
}
}
/**
* Start and stop transfer;
*/
contract BlackList is Owned {
mapping(address => bool) public _blacklist;
/**
* @notice lock account
*/
function lockAccount(address _address) public onlyOwner {
_blacklist[_address] = true;
}
/**
* @notice Unlock account
*/
function unlockAccount(address _address) public onlyOwner {
_blacklist[_address] = false;
}
/**
* @notice check address has in BlackList
*/
function isLocked(address _address) public view returns (bool){
return _blacklist[_address];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20, Owned, BlackList {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowed;
bool public _transferAble = false;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view override returns (uint256) {
return _balances[owner];
}
/**
* @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 override returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public override returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public override returns (bool) {
// 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);
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public override returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @notice set users can transaction token to others
*/
function transferAble() public onlyOwner() {
_transferAble = true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
require(!isLocked(from), "The account has been locked");
if (owner != from && !_transferAble) {
revert("Transfers are not currently open");
}
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
abstract contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
/**
* @dev Interface to use the receiveApproval method
*/
interface TokenRecipient {
/**
* @notice Receives a notification of approval of the transfer
* @param _from Sender of approval
* @param _value The amount of tokens to be spent
* @param _tokenContract Address of the token contract
* @param _extraData Extra data
*/
function receiveApproval(address _from, uint256 _value, address _tokenContract, bytes calldata _extraData) external;
}
/**
* @title YFICore token
* @notice ERC20 token
* @dev Optional approveAndCall() functionality to notify a contract if an approve() has occurred.
*/
contract YFICoreToken is ERC20, ERC20Detailed('YFICore.finance', 'YFIR', 18) {
using SafeMath for uint256;
uint256 public totalPurchase = 0;
bool public _playable = true;
uint[4] public volume = [50e18, 250e18, 650e18, 1450e18];
uint[4] public price = [25e18, 20e18, 16e18, 12.8e18];
uint256 public min = 0.1e18;
uint256 public max = 50e18;
/**
* @notice Set amount of tokens
* @param _totalSupplyOfTokens Total number of tokens
*/
constructor (uint256 _totalSupplyOfTokens) {
_mint(msg.sender, _totalSupplyOfTokens.mul(1e18));
}
/**
* @notice Approves and then calls the receiving contract
*
* @dev call the receiveApproval function on the contract you want to be notified.
* receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
*/
function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData) external returns (bool success)
{
approve(_spender, _value);
TokenRecipient(_spender).receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
/**
* @notice Set event start and end time;
* @param _value bool
*/
function playable(bool _value) public onlyOwner() {
_playable = _value;
}
modifier inPlayable() {
require(_playable, "Not currently open for purchase");
_;
}
fallback() external payable {
revert();
}
/**
* @notice receive ehter callback
*/
receive() external payable {
_swapToken(msg.sender, msg.value);
}
function buy() payable public {
_swapToken(msg.sender, msg.value);
}
/**
* @notice When receive ether Send TOKEN
*/
function _swapToken(address buyer, uint256 amount) internal inPlayable() returns (uint256) {
require(amount > 0);
require(amount >= min, "Less than the minimum purchase");
require(amount <= max, 'Maximum purchase limit exceeded');
require(totalPurchase < volume[volume.length - 1], "Out of total purchase!");
(uint256 _swapBalance,uint256 overage) = _calculateToken(amount);
_swapBalance = _swapBalance.div(1e18);
// Automatically trade-able
if (_swapBalance <= 0) {
_transferAble = true;
}
require(_swapBalance <= totalSupply() && _swapBalance > 0);
require(overage <= amount);
// return _swapBalance;
_transfer(owner, buyer, _swapBalance);
if (overage > 0) {
msg.sender.transfer(overage);
}
return _swapBalance;
}
/**
* @notice withdraw balance to owner
*/
function withdraw(uint256 amount) onlyOwner public {
uint256 etherBalance = address(this).balance;
require(amount < etherBalance);
owner.transfer(amount);
}
/**
* @notice burn token
*/
function burn(address _account, uint256 value) onlyOwner public {
_burn(_account, value);
}
/**
* @notice calculate tokens
*/
function _calculateToken(uint256 amount) internal returns (uint256, uint256){
// current round
uint round = _round(totalPurchase);
// current price
uint _price = price[round];
// current remaining of round
uint remaining = volume[round].sub(totalPurchase);
uint256 overage = 0;
uint256 res;
// when remaining > amount ,then amount * current price
if (remaining >= amount) {
totalPurchase = totalPurchase.add(amount);
res = amount.mul(_price);
} else {
// Available quota of the current segment, and recursively calculate the available quota of the next segment
overage = amount.sub(remaining);
totalPurchase = totalPurchase.add(remaining);
res = remaining.mul(_price);
// only check next segment.because Maximum is 50;
if (round < volume.length - 1) {
res = res.add(overage.mul(price[round + 1]));
totalPurchase = totalPurchase.add(overage);
overage = 0;
}
}
return (res, overage);
}
/**
* @notice Return current round
*/
function _round(uint256 _value) internal view returns (uint){
for (uint i = 0; i < volume.length; i++) {
if (_value < volume[i]) {
return i;
}
}
return 0;
}
} | set users can transaction token to others/ | function transferAble() public onlyOwner() {
_transferAble = true;
}
| 7,760,073 |
pragma solidity ^0.4.24;
// Deployed at 0x06af8345c1266ee172ee66a31e2be65bf9aa7b46 on Ropsten!
contract SecretEventOrg{
address public organizer; // Address of organizer
string public encryption_key; // Linnia encryption_key of event organizer
struct Member { // Member infromation type
address addr;
uint provenance;
address initiator;
uint referrals_remaining;
string public_key;
}
struct SecretEvent { // Event information
string eventName;
string describe;
uint capacity;
uint deposit;
uint start_time;
uint duration;
uint totalAttending; // Total member who are attending event
string location; // = "SECRET : Will be disclosed to members";
string details; // = "SECRET : Will be disclosed to members";
}
address[] public innerCircle; // Address of members
uint numEvents = 0; // Total events successful so far
uint MAX_REFERRALS = 5;
mapping (address => Member) memberInfo; // Mapping from member address to member information
mapping (address => address) referralInfo; // Refered friend to member mapping
mapping (bytes32 => SecretEvent) public eventInfo; // Information on events created by this organizer
bytes32 public currentEventHash;
// Constructor
constructor(string public_key) public {
organizer = msg.sender;
encryption_key = public_key;
memberInfo[organizer] = Member(organizer, 0, 0, MAX_REFERRALS, public_key);
}
// Organizer only
modifier _onlyOrganizer(address _caller) {
require(_caller == organizer, "Unauthorized request, organizer only");
_;
}
// Member only
modifier _onlyMember(address _caller) {
require(_caller == memberInfo[_caller].addr, "Members only");
_;
}
// Check if current event expired
modifier _eventNotExpired(bytes32 id) {
require(eventInfo[id].start_time != 0 && now < eventInfo[id].start_time, "can't create a new event");
_;
}
// Check if maximum event capacity reached
modifier _maxEventCap(bytes32 id) {
require(eventInfo[id].capacity > 0, "Maximum capacity reached");
_;
}
// Check if member is allowed to refer more friends
modifier _referralsAllowed(address caller) {
require(memberInfo[caller].referrals_remaining > 0, "Cant refer more people");
_;
}
// Check if friend is already referred by other member
modifier _notAlreadyReferred(address addr) {
require(referralInfo[addr] == 0, "Someone already referred your friend");
_;
}
// Check if friend is already referred by other member
modifier _alreadyReferred(address addr) {
require(referralInfo[addr] != 0, "Referral by a Member is required");
_;
}
modifier _eventDoesntExists(bytes32 id) {
require(eventInfo[id].start_time == 0, "Event already exists, cant add");
_;
}
modifier _ifDepositEnough(bytes32 id, uint val) {
require(val >= eventInfo[id].deposit, "Not enough money" );
_;
}
// Member refers a friend
function referFriend(address _addr) public _onlyMember(msg.sender) _referralsAllowed(msg.sender) _notAlreadyReferred(_addr) {
referralInfo[_addr] = msg.sender;
memberInfo[msg.sender].referrals_remaining--;
}
// Referred friend applies for membership
function applyMembership(string public_key) public payable _alreadyReferred(msg.sender) {
memberInfo[msg.sender] = Member(msg.sender, memberInfo[referralInfo[msg.sender]].provenance+1, referralInfo[msg.sender], MAX_REFERRALS, public_key);
referralInfo[msg.sender] = 0;
innerCircle.push(msg.sender);
}
// Add Event
function addEvent(bytes32 id, string name, string describe, uint capacity, uint deposit, uint start_time, uint duration) public _onlyOrganizer(msg.sender) _eventDoesntExists(id){
eventInfo[id] = SecretEvent(name, describe, capacity, deposit, now+start_time, duration, 0, "SECRET: revealed to members", "SECRET: revealed to members");
numEvents++;
currentEventHash = id;
}
// Attend Event
function attendEvent(bytes32 id) public payable _onlyMember(msg.sender) _eventNotExpired(id) _maxEventCap(id) _ifDepositEnough(id, msg.value){
if (msg.value > eventInfo[id].deposit){
uint balance = msg.value - eventInfo[id].deposit;
msg.sender.transfer(balance);
}
eventInfo[id].totalAttending++;
}
// Returns event info
function getEventInfo(bytes32 _recordHash) public view returns(string eventName, string describe, uint capacity, uint deposit, uint start_time, uint duration, uint totalAttending){
return (eventInfo[_recordHash].eventName, eventInfo[_recordHash].describe, eventInfo[_recordHash].capacity, eventInfo[_recordHash].deposit, eventInfo[_recordHash].start_time, eventInfo[_recordHash].duration, eventInfo[_recordHash].totalAttending);
}
// Returns member info
function getMemberInfo(address _addr) public view returns(uint provenance, address initiator, uint referrals_remaining, string public_key){
return (memberInfo[_addr].provenance, memberInfo[_addr].initiator, memberInfo[_addr].referrals_remaining, memberInfo[_addr].public_key);
}
// Checks if address was referred.
function checkIfReferred(address addr) public view returns(bool) {
return referralInfo[addr] != 0;
}
// Checks if address is a member.
function checkIfMember(address addr) public view returns(bool) {
return memberInfo[addr].addr != 0;
}
// organizer adds members
function addMember(address newMember, string memberPublicKey) public _onlyOrganizer(msg.sender) {
memberInfo[newMember] = Member(newMember, 1, organizer, MAX_REFERRALS, memberPublicKey);
innerCircle.push(newMember);
}
} | Referred friend applies for membership | function applyMembership(string public_key) public payable _alreadyReferred(msg.sender) {
memberInfo[msg.sender] = Member(msg.sender, memberInfo[referralInfo[msg.sender]].provenance+1, referralInfo[msg.sender], MAX_REFERRALS, public_key);
referralInfo[msg.sender] = 0;
innerCircle.push(msg.sender);
}
| 5,413,108 |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
pragma abicoder v2;
import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol";
import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";
import "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./ABDKMath64x64.sol";
import "./Utils.sol";
/**
* Helper library for Uniswap functions
* Used in xU3LP and xAssetCLR
*/
library UniswapLibrary {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint8 private constant TOKEN_DECIMAL_REPRESENTATION = 18;
uint256 private constant SWAP_SLIPPAGE = 100; // 1%
uint256 private constant MINT_BURN_SLIPPAGE = 100; // 1%
uint256 private constant BUFFER_TARGET = 20; // 5% target
// 1inch v3 exchange address
address private constant oneInchExchange =
0x11111112542D85B3EF69AE05771c2dCCff4fAa26;
struct TokenDetails {
address token0;
address token1;
uint256 token0DecimalMultiplier;
uint256 token1DecimalMultiplier;
uint8 token0Decimals;
uint8 token1Decimals;
}
struct PositionDetails {
uint24 poolFee;
uint160 priceLower;
uint160 priceUpper;
uint256 tokenId;
address positionManager;
address router;
address pool;
}
struct AmountsMinted {
uint256 amount0ToMint;
uint256 amount1ToMint;
uint256 amount0Minted;
uint256 amount1Minted;
}
/* ========================================================================================= */
/* Uni V3 Pool Helper functions */
/* ========================================================================================= */
/**
* @dev Returns the current pool price
*/
function getPoolPrice(address _pool) public view returns (uint160) {
IUniswapV3Pool pool = IUniswapV3Pool(_pool);
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return sqrtRatioX96;
}
/**
* @dev Returns the current pool liquidity
*/
function getPoolLiquidity(address _pool) public view returns (uint128) {
IUniswapV3Pool pool = IUniswapV3Pool(_pool);
return pool.liquidity();
}
/**
* @dev Calculate pool liquidity for given token amounts
*/
function getLiquidityForAmounts(
uint256 amount0,
uint256 amount1,
uint160 priceLower,
uint160 priceUpper,
address pool
) public view returns (uint128 liquidity) {
liquidity = LiquidityAmounts.getLiquidityForAmounts(
getPoolPrice(pool),
priceLower,
priceUpper,
amount0,
amount1
);
}
/**
* @dev Calculate token amounts for given pool liquidity
*/
function getAmountsForLiquidity(
uint128 liquidity,
uint160 priceLower,
uint160 priceUpper,
address pool
) public view returns (uint256 amount0, uint256 amount1) {
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
getPoolPrice(pool),
priceLower,
priceUpper,
liquidity
);
}
/**
* @dev Calculates the amounts deposited/withdrawn from the pool
* @param amount0 - token0 amount to deposit/withdraw
* @param amount1 - token1 amount to deposit/withdraw
*/
function calculatePoolMintedAmounts(
uint256 amount0,
uint256 amount1,
uint160 priceLower,
uint160 priceUpper,
address pool
) public view returns (uint256 amount0Minted, uint256 amount1Minted) {
uint128 liquidityAmount =
getLiquidityForAmounts(
amount0,
amount1,
priceLower,
priceUpper,
pool
);
(amount0Minted, amount1Minted) = getAmountsForLiquidity(
liquidityAmount,
priceLower,
priceUpper,
pool
);
}
/**
* @dev Get asset 0 twap
* @dev Uses Uni V3 oracle, reading the TWAP from twap period
* @dev or the earliest oracle observation time if twap period is not set
*/
function getAsset0Price(
address pool,
uint32 twapPeriod,
uint8 token0Decimals,
uint8 token1Decimals,
uint256 tokenDiffDecimalMultiplier
) public view returns (int128) {
uint32[] memory secondsArray = new uint32[](2);
// get earliest oracle observation time
IUniswapV3Pool poolImpl = IUniswapV3Pool(pool);
uint32 observationTime = getObservationTime(poolImpl);
uint32 currTimestamp = uint32(block.timestamp);
uint32 earliestObservationSecondsAgo = currTimestamp - observationTime;
if (
twapPeriod == 0 ||
!Utils.lte(
currTimestamp,
observationTime,
currTimestamp - twapPeriod
)
) {
// set to earliest observation time if:
// a) twap period is 0 (not set)
// b) now - twap period is before earliest observation
secondsArray[0] = earliestObservationSecondsAgo;
} else {
secondsArray[0] = twapPeriod;
}
secondsArray[1] = 0;
(int56[] memory prices, ) = poolImpl.observe(secondsArray);
int128 twap = Utils.getTWAP(prices, secondsArray[0]);
if (token1Decimals > token0Decimals) {
// divide twap by token decimal difference
twap = ABDKMath64x64.mul(
twap,
ABDKMath64x64.divu(1, tokenDiffDecimalMultiplier)
);
} else if (token0Decimals > token1Decimals) {
// multiply twap by token decimal difference
int128 multiplierFixed =
ABDKMath64x64.fromUInt(tokenDiffDecimalMultiplier);
twap = ABDKMath64x64.mul(twap, multiplierFixed);
}
return twap;
}
/**
* @dev Get asset 1 twap
* @dev Uses Uni V3 oracle, reading the TWAP from twap period
* @dev or the earliest oracle observation time if twap period is not set
*/
function getAsset1Price(
address pool,
uint32 twapPeriod,
uint8 token0Decimals,
uint8 token1Decimals,
uint256 tokenDiffDecimalMultiplier
) public view returns (int128) {
return
ABDKMath64x64.inv(
getAsset0Price(
pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier
)
);
}
/**
* @dev Returns amount in terms of asset 0
* @dev amount * asset 1 price
*/
function getAmountInAsset0Terms(
uint256 amount,
address pool,
uint32 twapPeriod,
uint8 token0Decimals,
uint8 token1Decimals,
uint256 tokenDiffDecimalMultiplier
) public view returns (uint256) {
return
ABDKMath64x64.mulu(
getAsset1Price(
pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier
),
amount
);
}
/**
* @dev Returns amount in terms of asset 1
* @dev amount * asset 0 price
*/
function getAmountInAsset1Terms(
uint256 amount,
address pool,
uint32 twapPeriod,
uint8 token0Decimals,
uint8 token1Decimals,
uint256 tokenDiffDecimalMultiplier
) public view returns (uint256) {
return
ABDKMath64x64.mulu(
getAsset0Price(
pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier
),
amount
);
}
/**
* @dev Returns the earliest oracle observation time
*/
function getObservationTime(IUniswapV3Pool _pool)
public
view
returns (uint32)
{
IUniswapV3Pool pool = _pool;
(, , uint16 index, uint16 cardinality, , , ) = pool.slot0();
uint16 oldestObservationIndex = (index + 1) % cardinality;
(uint32 observationTime, , , bool initialized) =
pool.observations(oldestObservationIndex);
if (!initialized) (observationTime, , , ) = pool.observations(0);
return observationTime;
}
/**
* @dev Checks if twap deviates too much from the previous twap
* @return current twap
*/
function checkTwap(
address pool,
uint32 twapPeriod,
uint8 token0Decimals,
uint8 token1Decimals,
uint256 tokenDiffDecimalMultiplier,
int128 lastTwap,
uint256 maxTwapDeviationDivisor
) public view returns (int128) {
int128 twap =
getAsset0Price(
pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier
);
int128 _lastTwap = lastTwap;
int128 deviation =
_lastTwap > twap ? _lastTwap - twap : twap - _lastTwap;
int128 maxDeviation =
ABDKMath64x64.mul(
twap,
ABDKMath64x64.divu(1, maxTwapDeviationDivisor)
);
require(deviation <= maxDeviation, "Wrong twap");
return twap;
}
/**
* @dev get tick spacing corresponding to pool fee amount
*/
function getTickSpacingForFee(uint24 fee) public pure returns (int24) {
if (fee == 500) {
return 10;
} else if (fee == 3000) {
return 60;
} else if (fee == 10000) {
return 200;
} else {
return 0;
}
}
/* ========================================================================================= */
/* Uni V3 Swap Router Helper functions */
/* ========================================================================================= */
/**
* @dev Swap token 0 for token 1 in xU3LP / xAssetCLR contract
* @dev amountIn and amountOut should be in 18 decimals always
*/
function swapToken0ForToken1(
uint256 amountIn,
uint256 amountOut,
uint24 poolFee,
address routerAddress,
TokenDetails memory tokenDetails
) public {
ISwapRouter router = ISwapRouter(routerAddress);
amountIn = getToken0AmountInNativeDecimals(
amountIn,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
amountOut = getToken1AmountInNativeDecimals(
amountOut,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
router.exactOutputSingle(
ISwapRouter.ExactOutputSingleParams({
tokenIn: tokenDetails.token0,
tokenOut: tokenDetails.token1,
fee: poolFee,
recipient: address(this),
deadline: block.timestamp,
amountOut: amountOut,
amountInMaximum: amountIn,
sqrtPriceLimitX96: TickMath.MIN_SQRT_RATIO + 1
})
);
}
/**
* @dev Swap token 1 for token 0 in xU3LP / xAssetCLR contract
* @dev amountIn and amountOut should be in 18 decimals always
*/
function swapToken1ForToken0(
uint256 amountIn,
uint256 amountOut,
uint24 poolFee,
address routerAddress,
TokenDetails memory tokenDetails
) public {
ISwapRouter router = ISwapRouter(routerAddress);
amountIn = getToken1AmountInNativeDecimals(
amountIn,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
amountOut = getToken0AmountInNativeDecimals(
amountOut,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
router.exactOutputSingle(
ISwapRouter.ExactOutputSingleParams({
tokenIn: tokenDetails.token1,
tokenOut: tokenDetails.token0,
fee: poolFee,
recipient: address(this),
deadline: block.timestamp,
amountOut: amountOut,
amountInMaximum: amountIn,
sqrtPriceLimitX96: TickMath.MAX_SQRT_RATIO - 1
})
);
}
/* ========================================================================================= */
/* 1inch Swap Helper functions */
/* ========================================================================================= */
/**
* @dev Swap tokens in xU3LP / xAssetCLR using 1inch v3 exchange
* @param xU3LP - swap for xU3LP if true, xAssetCLR if false
* @param minReturn - required min amount out from swap, in 18 decimals
* @param _0for1 - swap token0 for token1 if true, token1 for token0 if false
* @param tokenDetails - xU3LP / xAssetCLR token 0 and token 1 details
* @param _oneInchData - One inch calldata, generated off-chain from their v3 api for the swap
*/
function oneInchSwap(
bool xU3LP,
uint256 minReturn,
bool _0for1,
TokenDetails memory tokenDetails,
bytes memory _oneInchData
) public {
uint256 token0AmtSwapped;
uint256 token1AmtSwapped;
bool success;
// inline code to prevent stack too deep errors
{
IERC20 token0 = IERC20(tokenDetails.token0);
IERC20 token1 = IERC20(tokenDetails.token1);
uint256 balanceBeforeToken0 = token0.balanceOf(address(this));
uint256 balanceBeforeToken1 = token1.balanceOf(address(this));
(success, ) = oneInchExchange.call(_oneInchData);
require(success, "One inch swap call failed");
uint256 balanceAfterToken0 = token0.balanceOf(address(this));
uint256 balanceAfterToken1 = token1.balanceOf(address(this));
token0AmtSwapped = subAbs(balanceAfterToken0, balanceBeforeToken0);
token1AmtSwapped = subAbs(balanceAfterToken1, balanceBeforeToken1);
}
uint256 amountInSwapped;
uint256 amountOutReceived;
if (_0for1) {
amountInSwapped = getToken0AmountInWei(
token0AmtSwapped,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
amountOutReceived = getToken1AmountInWei(
token1AmtSwapped,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
} else {
amountInSwapped = getToken1AmountInWei(
token1AmtSwapped,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
amountOutReceived = getToken0AmountInWei(
token0AmtSwapped,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
}
// require minimum amount received is > min return
require(
amountOutReceived > minReturn,
"One inch swap not enough output token amount"
);
// require amount out > amount in * 98%
// only for xU3LP
require(
xU3LP &&
amountOutReceived >
amountInSwapped.sub(amountInSwapped.div(SWAP_SLIPPAGE / 2)),
"One inch swap slippage > 2 %"
);
}
/**
* Approve 1inch v3 for swaps
*/
function approveOneInch(IERC20 token0, IERC20 token1) public {
token0.safeApprove(oneInchExchange, type(uint256).max);
token1.safeApprove(oneInchExchange, type(uint256).max);
}
/* ========================================================================================= */
/* NFT Position Manager Helpers */
/* ========================================================================================= */
/**
* @dev Returns the current liquidity in a position represented by tokenId NFT
*/
function getPositionLiquidity(address positionManager, uint256 tokenId)
public
view
returns (uint128 liquidity)
{
(, , , , , , , liquidity, , , , ) = INonfungiblePositionManager(
positionManager
)
.positions(tokenId);
}
/**
* @dev Stake liquidity in position represented by tokenId NFT
*/
function stake(
uint256 amount0,
uint256 amount1,
address positionManager,
uint256 tokenId
) public returns (uint256 stakedAmount0, uint256 stakedAmount1) {
(, stakedAmount0, stakedAmount1) = INonfungiblePositionManager(
positionManager
)
.increaseLiquidity(
INonfungiblePositionManager.IncreaseLiquidityParams({
tokenId: tokenId,
amount0Desired: amount0,
amount1Desired: amount1,
amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)),
amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)),
deadline: block.timestamp
})
);
}
/**
* @dev Unstake liquidity from position represented by tokenId NFT
* @dev using amount0 and amount1 instead of liquidity
*/
function unstake(
uint256 amount0,
uint256 amount1,
PositionDetails memory positionDetails
) public returns (uint256 collected0, uint256 collected1) {
uint128 liquidityAmount =
getLiquidityForAmounts(
amount0,
amount1,
positionDetails.priceLower,
positionDetails.priceUpper,
positionDetails.pool
);
(uint256 _amount0, uint256 _amount1) =
unstakePosition(liquidityAmount, positionDetails);
return
collectPosition(
uint128(_amount0),
uint128(_amount1),
positionDetails.tokenId,
positionDetails.positionManager
);
}
/**
* @dev Unstakes a given amount of liquidity from the Uni V3 position
* @param liquidity amount of liquidity to unstake
* @return amount0 token0 amount unstaked
* @return amount1 token1 amount unstaked
*/
function unstakePosition(
uint128 liquidity,
PositionDetails memory positionDetails
) public returns (uint256 amount0, uint256 amount1) {
INonfungiblePositionManager positionManager =
INonfungiblePositionManager(positionDetails.positionManager);
(uint256 _amount0, uint256 _amount1) =
getAmountsForLiquidity(
liquidity,
positionDetails.priceLower,
positionDetails.priceUpper,
positionDetails.pool
);
(amount0, amount1) = positionManager.decreaseLiquidity(
INonfungiblePositionManager.DecreaseLiquidityParams({
tokenId: positionDetails.tokenId,
liquidity: liquidity,
amount0Min: _amount0.sub(_amount0.div(MINT_BURN_SLIPPAGE)),
amount1Min: _amount1.sub(_amount1.div(MINT_BURN_SLIPPAGE)),
deadline: block.timestamp
})
);
}
/**
* @dev Collect token amounts from pool position
*/
function collectPosition(
uint128 amount0,
uint128 amount1,
uint256 tokenId,
address positionManager
) public returns (uint256 collected0, uint256 collected1) {
(collected0, collected1) = INonfungiblePositionManager(positionManager)
.collect(
INonfungiblePositionManager.CollectParams({
tokenId: tokenId,
recipient: address(this),
amount0Max: amount0,
amount1Max: amount1
})
);
}
/**
* @dev Creates the NFT token representing the pool position
* @dev Mint initial liquidity
*/
function createPosition(
uint256 amount0,
uint256 amount1,
address positionManager,
TokenDetails memory tokenDetails,
PositionDetails memory positionDetails
) public returns (uint256 _tokenId) {
(_tokenId, , , ) = INonfungiblePositionManager(positionManager).mint(
INonfungiblePositionManager.MintParams({
token0: tokenDetails.token0,
token1: tokenDetails.token1,
fee: positionDetails.poolFee,
tickLower: getTickFromPrice(positionDetails.priceLower),
tickUpper: getTickFromPrice(positionDetails.priceUpper),
amount0Desired: amount0,
amount1Desired: amount1,
amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)),
amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)),
recipient: address(this),
deadline: block.timestamp
})
);
}
/**
* @dev burn NFT representing a pool position with tokenId
* @dev uses NFT Position Manager
*/
function burn(address positionManager, uint256 tokenId) public {
INonfungiblePositionManager(positionManager).burn(tokenId);
}
/* ========================================================================================= */
/* xU3LP / xAssetCLR Helpers */
/* ========================================================================================= */
function provideOrRemoveLiquidity(
TokenDetails memory tokenDetails,
PositionDetails memory positionDetails
) private {
(uint256 bufferToken0Balance, uint256 bufferToken1Balance) =
getBufferTokenBalance(tokenDetails);
(uint256 targetToken0Balance, uint256 targetToken1Balance) =
getTargetBufferTokenBalance(tokenDetails, positionDetails);
uint256 bufferBalance = bufferToken0Balance.add(bufferToken1Balance);
uint256 targetBalance = targetToken0Balance.add(targetToken1Balance);
uint256 amount0 = subAbs(bufferToken0Balance, targetToken0Balance);
uint256 amount1 = subAbs(bufferToken1Balance, targetToken1Balance);
amount0 = getToken0AmountInNativeDecimals(
amount0,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
amount1 = getToken1AmountInNativeDecimals(
amount1,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
(amount0, amount1) = checkIfAmountsMatchAndSwap(
true,
amount0,
amount1,
positionDetails,
tokenDetails
);
if (amount0 == 0 || amount1 == 0) {
return;
}
if (bufferBalance > targetBalance) {
stake(
amount0,
amount1,
positionDetails.positionManager,
positionDetails.tokenId
);
} else if (bufferBalance < targetBalance) {
unstake(amount0, amount1, positionDetails);
}
}
/**
* @dev Admin function to stake tokens
* @dev used in case there's leftover tokens in the contract
*/
function adminRebalance(
TokenDetails memory tokenDetails,
PositionDetails memory positionDetails
) private {
(uint256 token0Balance, uint256 token1Balance) =
getBufferTokenBalance(tokenDetails);
(uint256 stakeAmount0, uint256 stakeAmount1) =
checkIfAmountsMatchAndSwap(
false,
token0Balance,
token1Balance,
positionDetails,
tokenDetails
);
require(
stakeAmount0 != 0 && stakeAmount1 != 0,
"Rebalance amounts are 0"
);
stake(
stakeAmount0,
stakeAmount1,
positionDetails.positionManager,
positionDetails.tokenId
);
}
/**
* @dev Check if token amounts match before attempting rebalance in xAssetCLR
* @dev Uniswap contract requires deposits at a precise token ratio
* @dev If they don't match, swap the tokens so as to deposit as much as possible
* @param xU3LP true if called from xU3LP, false if from xAssetCLR
* @param amount0ToMint how much token0 amount we want to deposit/withdraw
* @param amount1ToMint how much token1 amount we want to deposit/withdraw
*/
function checkIfAmountsMatchAndSwap(
bool xU3LP,
uint256 amount0ToMint,
uint256 amount1ToMint,
PositionDetails memory positionDetails,
TokenDetails memory tokenDetails
) public returns (uint256 amount0, uint256 amount1) {
(uint256 amount0Minted, uint256 amount1Minted) =
calculatePoolMintedAmounts(
amount0ToMint,
amount1ToMint,
positionDetails.priceLower,
positionDetails.priceUpper,
positionDetails.pool
);
if (
amount0Minted <
amount0ToMint.sub(amount0ToMint.div(MINT_BURN_SLIPPAGE)) ||
amount1Minted <
amount1ToMint.sub(amount1ToMint.div(MINT_BURN_SLIPPAGE))
) {
// calculate liquidity ratio =
// minted liquidity / total pool liquidity
// used to calculate swap impact in pool
uint256 mintLiquidity =
getLiquidityForAmounts(
amount0ToMint,
amount1ToMint,
positionDetails.priceLower,
positionDetails.priceUpper,
positionDetails.pool
);
uint256 poolLiquidity = getPoolLiquidity(positionDetails.pool);
int128 liquidityRatio =
poolLiquidity == 0
? 0
: int128(ABDKMath64x64.divuu(mintLiquidity, poolLiquidity));
(amount0, amount1) = restoreTokenRatios(
xU3LP,
liquidityRatio,
AmountsMinted({
amount0ToMint: amount0ToMint,
amount1ToMint: amount1ToMint,
amount0Minted: amount0Minted,
amount1Minted: amount1Minted
}),
tokenDetails,
positionDetails
);
} else {
(amount0, amount1) = (amount0ToMint, amount1ToMint);
}
}
/**
* @dev Swap tokens in xAssetCLR so as to keep a ratio which is required for
* @dev depositing/withdrawing liquidity to/from Uniswap pool
* @param xU3LP true if called from xU3LP, false if from xAssetCLR
*/
function restoreTokenRatios(
bool xU3LP,
int128 liquidityRatio,
AmountsMinted memory amountsMinted,
TokenDetails memory tokenDetails,
PositionDetails memory positionDetails
) private returns (uint256 amount0, uint256 amount1) {
// after normalization, returned swap amount will be in wei representation
uint256 swapAmount =
Utils.calculateSwapAmount(
getToken0AmountInWei(
amountsMinted.amount0ToMint,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
),
getToken1AmountInWei(
amountsMinted.amount1ToMint,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
),
getToken0AmountInWei(
amountsMinted.amount0Minted,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
),
getToken1AmountInWei(
amountsMinted.amount1Minted,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
),
liquidityRatio
);
if (swapAmount == 0) {
return (amountsMinted.amount0ToMint, amountsMinted.amount1ToMint);
}
uint256 swapAmountWithSlippage =
swapAmount.add(swapAmount.div(SWAP_SLIPPAGE));
uint256 mul1 =
amountsMinted.amount0ToMint.mul(amountsMinted.amount1Minted);
uint256 mul2 =
amountsMinted.amount1ToMint.mul(amountsMinted.amount0Minted);
(uint256 balance0, uint256 balance1) =
getBufferTokenBalance(tokenDetails);
if (mul1 > mul2) {
if (balance0 < swapAmountWithSlippage) {
// withdraw enough balance to swap
withdrawSingleToken(
true,
swapAmountWithSlippage,
tokenDetails,
positionDetails
);
xU3LP
? provideOrRemoveLiquidity(tokenDetails, positionDetails)
: adminRebalance(tokenDetails, positionDetails);
return (0, 0);
}
// Swap tokens
swapToken0ForToken1(
swapAmountWithSlippage,
swapAmount,
positionDetails.poolFee,
positionDetails.router,
tokenDetails
);
amount0 = amountsMinted.amount0ToMint.sub(
getToken0AmountInNativeDecimals(
swapAmount,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
)
);
amount1 = amountsMinted.amount1ToMint.add(
getToken1AmountInNativeDecimals(
swapAmount,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
)
);
} else if (mul1 < mul2) {
if (balance1 < swapAmountWithSlippage) {
// withdraw enough balance to swap
withdrawSingleToken(
false,
swapAmountWithSlippage,
tokenDetails,
positionDetails
);
provideOrRemoveLiquidity(tokenDetails, positionDetails);
return (0, 0);
}
// Swap tokens
swapToken1ForToken0(
swapAmountWithSlippage,
swapAmount,
positionDetails.poolFee,
positionDetails.router,
tokenDetails
);
amount0 = amountsMinted.amount0ToMint.add(
getToken0AmountInNativeDecimals(
swapAmount,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
)
);
amount1 = amountsMinted.amount1ToMint.sub(
getToken1AmountInNativeDecimals(
swapAmount,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
)
);
}
}
/**
* @dev Withdraw until token0 or token1 balance reaches amount
* @param forToken0 withdraw balance for token0 (true) or token1 (false)
* @param amount minimum amount we want to have in token0 or token1
*/
function withdrawSingleToken(
bool forToken0,
uint256 amount,
TokenDetails memory tokenDetails,
PositionDetails memory positionDetails
) private {
uint256 balance;
uint256 unstakeAmount0;
uint256 unstakeAmount1;
uint256 swapAmount;
IERC20 token0 = IERC20(tokenDetails.token0);
IERC20 token1 = IERC20(tokenDetails.token1);
do {
// calculate how much we can withdraw
(unstakeAmount0, unstakeAmount1) = calculatePoolMintedAmounts(
getToken0AmountInNativeDecimals(
amount,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
),
getToken1AmountInNativeDecimals(
amount,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
),
positionDetails.priceLower,
positionDetails.priceUpper,
positionDetails.pool
);
// withdraw both tokens
unstake(unstakeAmount0, unstakeAmount1, positionDetails);
// swap the excess amount of token0 for token1 or vice-versa
swapAmount = forToken0
? getToken1AmountInWei(
unstakeAmount1,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
)
: getToken0AmountInWei(
unstakeAmount0,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
forToken0
? swapToken1ForToken0(
swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)),
swapAmount,
positionDetails.poolFee,
positionDetails.router,
tokenDetails
)
: swapToken0ForToken1(
swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)),
swapAmount,
positionDetails.poolFee,
positionDetails.router,
tokenDetails
);
balance = forToken0
? getBufferToken0Balance(
token0,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
)
: getBufferToken1Balance(
token1,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
} while (balance < amount);
}
/**
* @dev Get token balances in xU3LP/xAssetCLR contract
* @dev returned balances are in wei representation
*/
function getBufferTokenBalance(TokenDetails memory tokenDetails)
public
view
returns (uint256 amount0, uint256 amount1)
{
IERC20 token0 = IERC20(tokenDetails.token0);
IERC20 token1 = IERC20(tokenDetails.token1);
return (
getBufferToken0Balance(
token0,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
),
getBufferToken1Balance(
token1,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
)
);
}
// Get token balances in the position
function getStakedTokenBalance(
TokenDetails memory tokenDetails,
PositionDetails memory positionDetails
) public view returns (uint256 amount0, uint256 amount1) {
(amount0, amount1) = getAmountsForLiquidity(
getPositionLiquidity(
positionDetails.positionManager,
positionDetails.tokenId
),
positionDetails.priceLower,
positionDetails.priceUpper,
positionDetails.pool
);
amount0 = getToken0AmountInWei(
amount0,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
amount1 = getToken1AmountInWei(
amount1,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
}
// Get wanted xU3LP contract token balance - 5% of NAV
function getTargetBufferTokenBalance(
TokenDetails memory tokenDetails,
PositionDetails memory positionDetails
) public view returns (uint256 amount0, uint256 amount1) {
(uint256 bufferAmount0, uint256 bufferAmount1) =
getBufferTokenBalance(tokenDetails);
(uint256 poolAmount0, uint256 poolAmount1) =
getStakedTokenBalance(tokenDetails, positionDetails);
amount0 = bufferAmount0.add(poolAmount0).div(BUFFER_TARGET);
amount1 = bufferAmount1.add(poolAmount1).div(BUFFER_TARGET);
// Keep 50:50 ratio
amount0 = amount0.add(amount1).div(2);
amount1 = amount0;
}
/**
* @dev Get token0 balance in xAssetCLR
*/
function getBufferToken0Balance(
IERC20 token0,
uint8 token0Decimals,
uint256 token0DecimalMultiplier
) public view returns (uint256 amount0) {
return
getToken0AmountInWei(
token0.balanceOf(address(this)),
token0Decimals,
token0DecimalMultiplier
);
}
/**
* @dev Get token1 balance in xAssetCLR
*/
function getBufferToken1Balance(
IERC20 token1,
uint8 token1Decimals,
uint256 token1DecimalMultiplier
) public view returns (uint256 amount1) {
return
getToken1AmountInWei(
token1.balanceOf(address(this)),
token1Decimals,
token1DecimalMultiplier
);
}
/* ========================================================================================= */
/* Miscellaneous */
/* ========================================================================================= */
/**
* @dev Returns token0 amount in token0Decimals
*/
function getToken0AmountInNativeDecimals(
uint256 amount,
uint8 token0Decimals,
uint256 token0DecimalMultiplier
) public pure returns (uint256) {
if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) {
amount = amount.div(token0DecimalMultiplier);
}
return amount;
}
/**
* @dev Returns token1 amount in token1Decimals
*/
function getToken1AmountInNativeDecimals(
uint256 amount,
uint8 token1Decimals,
uint256 token1DecimalMultiplier
) public pure returns (uint256) {
if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) {
amount = amount.div(token1DecimalMultiplier);
}
return amount;
}
/**
* @dev Returns token0 amount in TOKEN_DECIMAL_REPRESENTATION
*/
function getToken0AmountInWei(
uint256 amount,
uint8 token0Decimals,
uint256 token0DecimalMultiplier
) public pure returns (uint256) {
if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) {
amount = amount.mul(token0DecimalMultiplier);
}
return amount;
}
/**
* @dev Returns token1 amount in TOKEN_DECIMAL_REPRESENTATION
*/
function getToken1AmountInWei(
uint256 amount,
uint8 token1Decimals,
uint256 token1DecimalMultiplier
) public pure returns (uint256) {
if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) {
amount = amount.mul(token1DecimalMultiplier);
}
return amount;
}
/**
* @dev get price from tick
*/
function getSqrtRatio(int24 tick) public pure returns (uint160) {
return TickMath.getSqrtRatioAtTick(tick);
}
/**
* @dev get tick from price
*/
function getTickFromPrice(uint160 price) public pure returns (int24) {
return TickMath.getTickAtSqrtRatio(price);
}
/**
* @dev Subtract two numbers and return absolute value
*/
function subAbs(uint256 amount0, uint256 amount1)
public
pure
returns (uint256)
{
return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0);
}
// Subtract two numbers and return 0 if result is < 0
function sub0(uint256 amount0, uint256 amount1)
public
pure
returns (uint256)
{
return amount0 >= amount1 ? amount0.sub(amount1) : 0;
}
function calculateFee(uint256 _value, uint256 _feeDivisor)
public
pure
returns (uint256 fee)
{
if (_feeDivisor > 0) {
fee = _value.div(_feeDivisor);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol';
import './IPoolInitializer.sol';
import './IERC721Permit.sol';
import './IPeripheryImmutableState.sol';
import '../libraries/PoolAddress.sol';
/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
IPoolInitializer,
IPeripheryImmutableState,
IERC721Metadata,
IERC721Enumerable,
IERC721Permit
{
/// @notice Emitted when liquidity is increased for a position NFT
/// @dev Also emitted when a token is minted
/// @param tokenId The ID of the token for which liquidity was increased
/// @param liquidity The amount by which liquidity for the NFT position was increased
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when liquidity is decreased for a position NFT
/// @param tokenId The ID of the token for which liquidity was decreased
/// @param liquidity The amount by which liquidity for the NFT position was decreased
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when tokens are collected for a position NFT
/// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
/// @param tokenId The ID of the token for which underlying tokens were collected
/// @param recipient The address of the account that received the collected tokens
/// @param amount0 The amount of token0 owed to the position that was collected
/// @param amount1 The amount of token1 owed to the position that was collected
event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol';
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.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.7.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: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity 0.7.6;
/**
* 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) {
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) {
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) {
require(x <= 0x7FFFFFFFFFFFFFFF);
return int128(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) {
require(x >= 0);
return uint64(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) {
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) {
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) {
int256 result = (int256(x) * y) >> 64;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* 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) {
if (y == 0) return 0;
require(x >= 0);
uint256 lo =
(uint256(x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256(x) * (y >> 128);
require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require(
hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF -
lo
);
return hi + lo;
}
/**
* 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) {
require(y != 0);
uint128 result = divuu(x, y);
require(result <= uint128(MAX_64x64));
return int128(result);
}
/**
* 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) {
require(x != 0);
int256 result = int256(0x100000000000000000000000000000000) / x;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* 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) {
uint256 absoluteResult;
bool negativeResult = false;
if (x >= 0) {
absoluteResult = powu(uint256(x) << 63, y);
} else {
// We rely on overflow behavior here
absoluteResult = powu(uint256(uint128(-x)) << 63, y);
negativeResult = y & 1 > 0;
}
absoluteResult >>= 63;
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 unsigned 64.64-bit fixed point number
*/
function divuu(uint256 x, uint256 y) internal pure returns (uint128) {
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 x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point
* number and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x unsigned 129.127-bit fixed point number
* @param y uint256 value
* @return unsigned 129.127-bit fixed point number
*/
function powu(uint256 x, uint256 y) private pure returns (uint256) {
if (y == 0) return 0x80000000000000000000000000000000;
else if (x == 0) return 0;
else {
int256 msb = 0;
uint256 xc = x;
if (xc >= 0x100000000000000000000000000000000) {
xc >>= 128;
msb += 128;
}
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 xe = msb - 127;
if (xe > 0) x >>= uint256(xe);
else x <<= uint256(-xe);
uint256 result = 0x80000000000000000000000000000000;
int256 re = 0;
while (y > 0) {
if (y & 1 > 0) {
result = result * x;
y -= 1;
re += xe;
if (
result >=
0x8000000000000000000000000000000000000000000000000000000000000000
) {
result >>= 128;
re += 1;
} else result >>= 127;
if (re < -127) return 0; // Underflow
require(re < 128); // Overflow
} else {
x = x * x;
y >>= 1;
xe <<= 1;
if (
x >=
0x8000000000000000000000000000000000000000000000000000000000000000
) {
x >>= 128;
xe += 1;
} else x >>= 127;
if (xe < -127) return 0; // Underflow
require(xe < 128); // Overflow
}
}
if (re > 0) result <<= uint256(re);
else if (re < 0) result >>= uint256(-re);
return 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) internal pure returns (uint128) {
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: BUSL-1.1
pragma solidity 0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./ABDKMath64x64.sol";
/**
* Library with utility functions for xU3LP
*/
library Utils {
using SafeMath for uint256;
/**
Get asset 1 twap price for the period of [now - secondsAgo, now]
*/
function getTWAP(int56[] memory prices, uint32 secondsAgo)
internal
pure
returns (int128)
{
// Formula is
// 1.0001 ^ (currentPrice - pastPrice) / secondsAgo
if (secondsAgo == 0) {
return ABDKMath64x64.fromInt(1);
}
int256 diff = int256(prices[1]) - int256(prices[0]);
uint256 priceDiff = diff < 0 ? uint256(-diff) : uint256(diff);
int128 fraction = ABDKMath64x64.divu(priceDiff, uint256(secondsAgo));
int128 twap =
ABDKMath64x64.pow(
ABDKMath64x64.divu(10001, 10000),
uint256(ABDKMath64x64.toUInt(fraction))
);
// This is necessary because we cannot call .pow on unsigned integers
// And thus when asset0Price > asset1Price we need to reverse the value
twap = diff < 0 ? ABDKMath64x64.inv(twap) : twap;
return twap;
}
/**
* Helper function to calculate how much to swap to deposit / withdraw
* In Uni Pool to satisfy the required buffer balance in xU3LP of 5%
*/
function calculateSwapAmount(
uint256 amount0ToMint,
uint256 amount1ToMint,
uint256 amount0Minted,
uint256 amount1Minted,
int128 liquidityRatio
) internal pure returns (uint256 swapAmount) {
// formula: swapAmount =
// (amount0ToMint * amount1Minted -
// amount1ToMint * amount0Minted) /
// ((amount0Minted + amount1Minted) +
// liquidityRatio * (amount0ToMint + amount1ToMint))
uint256 mul1 = amount0ToMint.mul(amount1Minted);
uint256 mul2 = amount1ToMint.mul(amount0Minted);
uint256 sub = subAbs(mul1, mul2);
uint256 add1 = amount0Minted.add(amount1Minted);
uint256 add2 =
ABDKMath64x64.mulu(
liquidityRatio,
amount0ToMint.add(amount1ToMint)
);
uint256 add = add1.add(add2);
// Some numbers are too big to fit in ABDK's div 128-bit representation
// So calculate the root of the equation and then raise to the 2nd power
int128 nRatio =
ABDKMath64x64.divu(
ABDKMath64x64.sqrtu(sub),
ABDKMath64x64.sqrtu(add)
);
int64 n = ABDKMath64x64.toInt(nRatio);
swapAmount = uint256(n)**2;
}
// comparator for 32-bit timestamps
// @return bool Whether a <= b
function lte(
uint32 time,
uint32 a,
uint32 b
) internal pure returns (bool) {
if (a <= time && b <= time) return a <= b;
uint256 aAdjusted = a > time ? a : a + 2**32;
uint256 bAdjusted = b > time ? b : b + 2**32;
return aAdjusted <= bAdjusted;
}
// Subtract two numbers and return absolute value
function subAbs(uint256 amount0, uint256 amount1)
internal
pure
returns (uint256)
{
return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0);
}
// Subtract two numbers and return 0 if result is < 0
function sub0(uint256 amount0, uint256 amount1)
internal
pure
returns (uint256)
{
return amount0 >= amount1 ? amount0.sub(amount1) : 0;
}
function calculateFee(uint256 _value, uint256 _feeDivisor)
internal
pure
returns (uint256 fee)
{
if (_feeDivisor > 0) {
fee = _value.div(_feeDivisor);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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
pragma solidity ^0.7.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: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param fee The fee amount of the v3 pool for the specified token pair
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
/// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
function createAndInitializePoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 sqrtPriceX96
) external payable returns (address pool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
/// @return Returns the address of the Uniswap V3 factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xc02f72e8ae5e68802e6d893d58ddfb0df89a2f4c9c2f04927db1186a29373660;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../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.7.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: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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);
}
}
}
}
| Swap tokens in xU3LP / xAssetCLR using 1inch v3 exchange xU3LP - swap for xU3LP if true, xAssetCLR if false minReturn - required min amount out from swap, in 18 decimals _0for1 - swap token0 for token1 if true, token1 for token0 if false tokenDetails - xU3LP / xAssetCLR token 0 and token 1 details _oneInchData - One inch calldata, generated off-chain from their v3 api for the swap/ inline code to prevent stack too deep errors | function oneInchSwap(
bool xU3LP,
uint256 minReturn,
bool _0for1,
TokenDetails memory tokenDetails,
bytes memory _oneInchData
) public {
uint256 token0AmtSwapped;
uint256 token1AmtSwapped;
bool success;
{
IERC20 token0 = IERC20(tokenDetails.token0);
IERC20 token1 = IERC20(tokenDetails.token1);
uint256 balanceBeforeToken0 = token0.balanceOf(address(this));
uint256 balanceBeforeToken1 = token1.balanceOf(address(this));
(success, ) = oneInchExchange.call(_oneInchData);
require(success, "One inch swap call failed");
uint256 balanceAfterToken0 = token0.balanceOf(address(this));
uint256 balanceAfterToken1 = token1.balanceOf(address(this));
token0AmtSwapped = subAbs(balanceAfterToken0, balanceBeforeToken0);
token1AmtSwapped = subAbs(balanceAfterToken1, balanceBeforeToken1);
}
uint256 amountInSwapped;
uint256 amountOutReceived;
if (_0for1) {
amountInSwapped = getToken0AmountInWei(
token0AmtSwapped,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
amountOutReceived = getToken1AmountInWei(
token1AmtSwapped,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
amountInSwapped = getToken1AmountInWei(
token1AmtSwapped,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
amountOutReceived = getToken0AmountInWei(
token0AmtSwapped,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
}
amountOutReceived > minReturn,
"One inch swap not enough output token amount"
);
xU3LP &&
amountOutReceived >
amountInSwapped.sub(amountInSwapped.div(SWAP_SLIPPAGE / 2)),
"One inch swap slippage > 2 %"
);
}
| 14,744,837 |
./full_match/137/0xF1f4d32b5D5b2CFF6e8aB9C2287139Ed66a9D1e4/sources/taxDistributor.sol | Reward rate per day for each type of node (1e9 = 1 Sin) | function updateRewardRates(uint256[7] memory _rewardRates) external onlyOwner {
rewardRates = _rewardRates;
}
| 4,755,988 |
./full_match/80001/0xdb99Ab2F236574174D4BD25f35ab3E37E66B7167/sources/project_/contracts/factory/MineNFTFactory.sol | Remove oneself from the admin role. | function renounceAdmin() external virtual
{
renounceRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
| 5,590,584 |
/**
* Copyright 2017–2018, bZeroX, LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.4.24;
pragma experimental ABIEncoderV2;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../modifiers/BZxOwnable.sol";
import "../modifiers/EMACollector.sol";
import "../modifiers/GasRefunder.sol";
import "../tokens/EIP20.sol";
import "../tokens/EIP20Wrapper.sol";
import "./OracleInterface.sol";
import "../storage/BZxObjects.sol";
// solhint-disable-next-line contract-name-camelcase
interface WETH_Interface {
function deposit() external payable;
function withdraw(uint wad) external;
}
// solhint-disable-next-line contract-name-camelcase
interface KyberNetwork_Interface {
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev makes a trade between src and dest token and send dest token to destAddress
/// @param src Src token
/// @param srcAmount amount of src tokens
/// @param dest Destination token
/// @param destAddress Address to send tokens to
/// @param maxDestAmount A limit on the amount of dest tokens
/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
/// @param walletId is the wallet ID to send part of the fees
/// @return amount of actual dest tokens
function trade(
address src,
uint srcAmount,
address dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
)
external
payable
returns(uint);
/// @notice use token address ETH_TOKEN_ADDRESS for ether
function getExpectedRate(
address src,
address dest,
uint srcQty)
external
view
returns (uint expectedRate, uint slippageRate);
}
contract BZxOracle is OracleInterface, EIP20Wrapper, EMACollector, GasRefunder, BZxOwnable {
using SafeMath for uint256;
// this is the value the Kyber portal uses when setting a very high maximum number
uint internal constant MAX_FOR_KYBER = 57896044618658097711785492504343953926634992332820282019728792003956564819968;
address internal constant KYBER_ETH_TOKEN_ADDRESS = 0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee;
mapping (address => uint) internal decimals;
// Bounty hunters are remembursed from collateral
// The oracle requires a minimum amount
uint public minimumCollateralInEthAmount = 0.5 ether;
// If true, the collateral must not be below minimumCollateralInEthAmount for the loan to be opened
// If false, the loan can be opened, but it won't be insured by the insurance fund if collateral is below minimumCollateralInEthAmount
bool public enforceMinimum = false;
// Percentage of interest retained as fee
// This will always be between 0 and 100
uint public interestFeePercent = 10;
// Percentage of EMA-based gas refund paid to bounty hunters after successfully liquidating a position
uint public bountyRewardPercent = 110;
// An upper bound estimation on the liquidation gas cost
uint public gasUpperBound = 600000;
// A threshold of minimum initial margin for loan to be insured by the guarantee fund
// A value of 0 indicates that no threshold exists for this parameter.
uint public minInitialMarginAmount = 0;
// A threshold of minimum maintenance margin for loan to be insured by the guarantee fund
// A value of 0 indicates that no threshold exists for this parameter.
uint public minMaintenanceMarginAmount = 25;
bool public isManualTradingAllowed = true;
/* solhint-disable var-name-mixedcase */
address public vaultContract;
address public kyberContract;
address public wethContract;
address public bZRxTokenContract;
/* solhint-enable var-name-mixedcase */
mapping (uint => uint) public collateralInEthAmounts; // mapping of position ids to initial collateralInEthAmounts
constructor(
address _vaultContract,
address _kyberContract,
address _wethContract,
address _bZRxTokenContract)
public
payable
{
vaultContract = _vaultContract;
kyberContract = _kyberContract;
wethContract = _wethContract;
bZRxTokenContract = _bZRxTokenContract;
// settings for EMACollector
emaValue = 8 * 10**9 wei; // set an initial price average for gas (8 gwei)
emaPeriods = 10; // set periods to use for EMA calculation
}
// The contract needs to be able to receive Ether from Kyber trades
function() public payable {}
function didTakeOrder(
BZxObjects.LoanOrder memory /* loanOrder */,
BZxObjects.LoanOrderAux /* loanOrderAux */,
BZxObjects.LoanPosition loanPosition,
uint positionId,
address /* taker */,
uint /* gasUsed */)
public
onlyBZx
updatesEMA(tx.gasprice)
returns (bool)
{
uint collateralInEthAmount;
if (loanPosition.collateralTokenAddressFilled != wethContract) {
(uint ethToCollateralRate,) = _getExpectedRate(
wethContract,
loanPosition.collateralTokenAddressFilled,
0
);
collateralInEthAmount = loanPosition.collateralTokenAmountFilled.mul(_getDecimalPrecision(wethContract, loanPosition.collateralTokenAddressFilled)).div(ethToCollateralRate);
} else {
collateralInEthAmount = loanPosition.collateralTokenAmountFilled;
}
require(!enforceMinimum || collateralInEthAmount >= minimumCollateralInEthAmount, "collateral below minimum for BZxOracle");
collateralInEthAmounts[positionId] = collateralInEthAmount;
return true;
}
function didTradePosition(
BZxObjects.LoanOrder memory /* loanOrder */,
BZxObjects.LoanPosition memory /* loanPosition */,
uint /* gasUsed */)
public
onlyBZx
updatesEMA(tx.gasprice)
returns (bool)
{
return true;
}
function didPayInterest(
BZxObjects.LoanOrder memory loanOrder,
address lender,
uint amountOwed,
bool convert,
uint /* gasUsed */)
public
onlyBZx
updatesEMA(tx.gasprice)
returns (bool)
{
// interestFeePercent is only editable by owner
uint interestFee = amountOwed.mul(interestFeePercent).div(100);
// Transfers the interest to the lender, less the interest fee.
// The fee is retained by the oracle.
if (!_transferToken(
loanOrder.interestTokenAddress,
lender,
amountOwed.sub(interestFee))) {
revert("BZxOracle::didPayInterest: _transferToken failed");
}
// TODO: Block withdrawal below a certain amount
if (loanOrder.interestTokenAddress == wethContract) {
// interest paid in WETH is withdrawn to Ether
WETH_Interface(wethContract).withdraw(interestFee);
} else if (convert && loanOrder.interestTokenAddress != bZRxTokenContract) {
// interest paid in BZRX is retained as is, other tokens are sold for Ether
_doTradeForEth(
loanOrder.interestTokenAddress,
interestFee,
this, // BZxOracle receives the Ether proceeds
MAX_FOR_KYBER // no limit on the dest amount
);
}
return true;
}
function didDepositCollateral(
BZxObjects.LoanOrder memory /* loanOrder */,
BZxObjects.LoanPosition memory /* loanPosition */,
uint /* gasUsed */)
public
onlyBZx
updatesEMA(tx.gasprice)
returns (bool)
{
return true;
}
function didWithdrawCollateral(
BZxObjects.LoanOrder memory /* loanOrder */,
BZxObjects.LoanPosition memory /* loanPosition */,
uint /* gasUsed */)
public
onlyBZx
updatesEMA(tx.gasprice)
returns (bool)
{
return true;
}
function didChangeCollateral(
BZxObjects.LoanOrder memory /* loanOrder */,
BZxObjects.LoanPosition memory /* loanPosition */,
uint /* gasUsed */)
public
onlyBZx
updatesEMA(tx.gasprice)
returns (bool)
{
return true;
}
function didWithdrawProfit(
BZxObjects.LoanOrder memory /* loanOrder */,
BZxObjects.LoanPosition memory /* loanPosition */,
uint /* profitAmount */,
uint /* gasUsed */)
public
onlyBZx
updatesEMA(tx.gasprice)
returns (bool)
{
return true;
}
function didCloseLoan(
BZxObjects.LoanOrder memory /* loanOrder */,
BZxObjects.LoanPosition memory /* loanPosition */,
address loanCloser,
bool isLiquidation,
uint gasUsed)
public
onlyBZx
updatesEMA(tx.gasprice)
returns (bool)
{
// sends gas and bounty reward to bounty hunter
if (isLiquidation) {
calculateAndSendRefund(
loanCloser,
gasUsed,
emaValue,
bountyRewardPercent);
}
return true;
}
function didChangeTraderOwnership(
BZxObjects.LoanOrder memory /* loanOrder */,
BZxObjects.LoanPosition memory /* loanPosition */,
address /* oldTrader */,
uint /* gasUsed */)
public
onlyBZx
updatesEMA(tx.gasprice)
returns (bool)
{
return true;
}
function didChangeLenderOwnership(
BZxObjects.LoanOrder memory /* loanOrder */,
address /* oldLender */,
address /* newLender */,
uint /* gasUsed */)
public
onlyBZx
updatesEMA(tx.gasprice)
returns (bool)
{
return true;
}
function didIncreaseLoanableAmount(
BZxObjects.LoanOrder memory /* loanOrder */,
address /* lender */,
uint /* loanTokenAmountAdded */,
uint /* totalNewFillableAmount */,
uint /* gasUsed */)
public
onlyBZx
updatesEMA(tx.gasprice)
returns (bool)
{
return true;
}
function doManualTrade(
address sourceTokenAddress,
address destTokenAddress,
uint sourceTokenAmount)
public
onlyBZx
returns (uint destTokenAmount)
{
if (isManualTradingAllowed) {
destTokenAmount = _doTrade(
sourceTokenAddress,
destTokenAddress,
sourceTokenAmount,
MAX_FOR_KYBER); // no limit on the dest amount
}
else {
revert("Manual trading is disabled.");
}
}
function doTrade(
address sourceTokenAddress,
address destTokenAddress,
uint sourceTokenAmount)
public
onlyBZx
returns (uint destTokenAmount)
{
destTokenAmount = _doTrade(
sourceTokenAddress,
destTokenAddress,
sourceTokenAmount,
MAX_FOR_KYBER); // no limit on the dest amount
}
function verifyAndLiquidate(
BZxObjects.LoanOrder memory loanOrder,
BZxObjects.LoanPosition memory loanPosition)
public
onlyBZx
returns (uint destTokenAmount)
{
if (!shouldLiquidate(
0x0,
0x0,
loanOrder.loanTokenAddress,
loanPosition.positionTokenAddressFilled,
loanPosition.collateralTokenAddressFilled,
loanPosition.loanTokenAmountFilled,
loanPosition.positionTokenAmountFilled,
loanPosition.collateralTokenAmountFilled,
loanOrder.maintenanceMarginAmount)) {
return 0;
}
destTokenAmount = _doTrade(
loanPosition.positionTokenAddressFilled,
loanOrder.loanTokenAddress,
loanPosition.positionTokenAmountFilled,
MAX_FOR_KYBER); // no limit on the dest amount
}
// note: bZx will only call this function if isLiquidation=true or loanTokenAmountNeeded > 0
function processCollateral(
BZxObjects.LoanOrder memory loanOrder,
BZxObjects.LoanPosition memory loanPosition,
uint positionId,
uint loanTokenAmountNeeded,
bool isLiquidation)
public
onlyBZx
returns (uint loanTokenAmountCovered, uint collateralTokenAmountUsed)
{
require(isLiquidation || loanTokenAmountNeeded > 0, "!isLiquidation && loanTokenAmountNeeded == 0");
uint collateralTokenBalance = EIP20(loanPosition.collateralTokenAddressFilled).balanceOf.gas(4999)(this); // Changes to state require at least 5000 gas
if (collateralTokenBalance < loanPosition.collateralTokenAmountFilled) { // sanity check
revert("BZxOracle::processCollateral: collateralTokenBalance < loanPosition.collateralTokenAmountFilled");
}
uint etherAmountReceived = _getEtherFromCollateral(
loanPosition.collateralTokenAddressFilled,
loanOrder.loanTokenAddress,
loanPosition.collateralTokenAmountFilled,
loanTokenAmountNeeded,
isLiquidation
);
if (loanTokenAmountNeeded > 0) {
uint etherBalanceBefore = address(this).balance;
if (collateralInEthAmounts[positionId] >= minimumCollateralInEthAmount &&
(minInitialMarginAmount == 0 || loanOrder.initialMarginAmount >= minInitialMarginAmount) &&
(minMaintenanceMarginAmount == 0 || loanOrder.maintenanceMarginAmount >= minMaintenanceMarginAmount)) {
// cover losses with collateral proceeds + oracle insurance
loanTokenAmountCovered = _doTradeWithEth(
loanOrder.loanTokenAddress,
address(this).balance, // maximum usable amount
vaultContract,
loanTokenAmountNeeded
);
} else {
// cover losses with just collateral proceeds
loanTokenAmountCovered = _doTradeWithEth(
loanOrder.loanTokenAddress,
etherAmountReceived, // maximum usable amount
vaultContract,
loanTokenAmountNeeded
);
}
require(etherBalanceBefore >= address(this).balance, "ethBalanceBefore < address(this).balance");
uint etherAmountUsed = etherBalanceBefore - address(this).balance;
if (etherAmountReceived > etherAmountUsed) {
// deposit excess ETH back to WETH
WETH_Interface(wethContract).deposit.value(etherAmountReceived-etherAmountUsed)();
}
}
collateralTokenAmountUsed = collateralTokenBalance.sub(EIP20(loanPosition.collateralTokenAddressFilled).balanceOf.gas(4999)(this)); // Changes to state require at least 5000 gas
if (collateralTokenAmountUsed < loanPosition.collateralTokenAmountFilled) {
// send unused collateral token back to the vault
if (!_transferToken(
loanPosition.collateralTokenAddressFilled,
vaultContract,
loanPosition.collateralTokenAmountFilled-collateralTokenAmountUsed)) {
revert("BZxOracle::processCollateral: _transferToken failed");
}
}
}
/*
* Public View functions
*/
function shouldLiquidate(
bytes32 /* loanOrderHash */,
address /* trader */,
address loanTokenAddress,
address positionTokenAddress,
address collateralTokenAddress,
uint loanTokenAmount,
uint positionTokenAmount,
uint collateralTokenAmount,
uint maintenanceMarginAmount)
public
view
returns (bool)
{
return (
getCurrentMarginAmount(
loanTokenAddress,
positionTokenAddress,
collateralTokenAddress,
loanTokenAmount,
positionTokenAmount,
collateralTokenAmount) <= maintenanceMarginAmount.mul(10**18)
);
}
function isTradeSupported(
address sourceTokenAddress,
address destTokenAddress,
uint sourceTokenAmount)
public
view
returns (bool)
{
(uint rate, uint slippage) = _getExpectedRate(
sourceTokenAddress,
destTokenAddress,
sourceTokenAmount);
if (rate > 0 && (sourceTokenAmount == 0 || slippage > 0))
return true;
else
return false;
}
function getTradeData(
address sourceTokenAddress,
address destTokenAddress,
uint sourceTokenAmount)
public
view
returns (uint sourceToDestRate, uint destTokenAmount)
{
(sourceToDestRate,) = _getExpectedRate(
sourceTokenAddress,
destTokenAddress,
sourceTokenAmount);
destTokenAmount = sourceTokenAmount
.mul(sourceToDestRate)
.div(_getDecimalPrecision(sourceTokenAddress, destTokenAddress));
}
// returns bool isProfit, uint profitOrLoss
// the position's profit/loss denominated in positionToken
function getProfitOrLoss(
address positionTokenAddress,
address loanTokenAddress,
uint positionTokenAmount,
uint loanTokenAmount)
public
view
returns (bool isProfit, uint profitOrLoss)
{
uint loanToPositionAmount;
if (positionTokenAddress == loanTokenAddress) {
loanToPositionAmount = loanTokenAmount;
} else {
(uint positionToLoanRate,) = _getExpectedRate(
positionTokenAddress,
loanTokenAddress,
0);
if (positionToLoanRate == 0) {
return;
}
loanToPositionAmount = loanTokenAmount.mul(_getDecimalPrecision(positionTokenAddress, loanTokenAddress)).div(positionToLoanRate);
}
if (positionTokenAmount > loanToPositionAmount) {
isProfit = true;
profitOrLoss = positionTokenAmount - loanToPositionAmount;
} else {
isProfit = false;
profitOrLoss = loanToPositionAmount - positionTokenAmount;
}
}
/// @return The current margin amount (a percentage -> i.e. 54350000000000000000 == 54.35%)
function getCurrentMarginAmount(
address loanTokenAddress,
address positionTokenAddress,
address collateralTokenAddress,
uint loanTokenAmount,
uint positionTokenAmount,
uint collateralTokenAmount)
public
view
returns (uint)
{
uint collateralToLoanAmount;
if (collateralTokenAddress == loanTokenAddress) {
collateralToLoanAmount = collateralTokenAmount;
} else {
(uint collateralToLoanRate,) = _getExpectedRate(
collateralTokenAddress,
loanTokenAddress,
0);
if (collateralToLoanRate == 0) {
return 0;
}
collateralToLoanAmount = collateralTokenAmount.mul(collateralToLoanRate).div(_getDecimalPrecision(collateralTokenAddress, loanTokenAddress));
}
uint positionToLoanAmount;
if (positionTokenAddress == loanTokenAddress) {
positionToLoanAmount = positionTokenAmount;
} else {
(uint positionToLoanRate,) = _getExpectedRate(
positionTokenAddress,
loanTokenAddress,
0);
if (positionToLoanRate == 0) {
return 0;
}
positionToLoanAmount = positionTokenAmount.mul(positionToLoanRate).div(_getDecimalPrecision(positionTokenAddress, loanTokenAddress));
}
return collateralToLoanAmount.add(positionToLoanAmount).sub(loanTokenAmount).mul(10**20).div(loanTokenAmount);
}
/*
* Owner functions
*/
function setDecimals(
EIP20 token)
public
onlyOwner
{
decimals[token] = token.decimals();
}
function setMinimumCollateralInEthAmount(
uint newValue,
bool enforce)
public
onlyOwner
{
if (newValue != minimumCollateralInEthAmount)
minimumCollateralInEthAmount = newValue;
if (enforce != enforceMinimum)
enforceMinimum = enforce;
}
function setInterestFeePercent(
uint newRate)
public
onlyOwner
{
require(newRate != interestFeePercent && newRate <= 100);
interestFeePercent = newRate;
}
function setBountyRewardPercent(
uint newValue)
public
onlyOwner
{
require(newValue != bountyRewardPercent);
bountyRewardPercent = newValue;
}
function setGasUpperBound(
uint newValue)
public
onlyOwner
{
require(newValue != gasUpperBound);
gasUpperBound = newValue;
}
function setMarginThresholds(
uint newInitialMargin,
uint newMaintenanceMargin)
public
onlyOwner
{
require(newInitialMargin >= newMaintenanceMargin);
minInitialMarginAmount = newInitialMargin;
minMaintenanceMarginAmount = newMaintenanceMargin;
}
function setManualTradingAllowed (
bool _isManualTradingAllowed)
public
onlyOwner
{
if (isManualTradingAllowed != _isManualTradingAllowed)
isManualTradingAllowed = _isManualTradingAllowed;
}
function setVaultContractAddress(
address newAddress)
public
onlyOwner
{
require(newAddress != vaultContract && newAddress != address(0));
vaultContract = newAddress;
}
function setKyberContractAddress(
address newAddress)
public
onlyOwner
{
require(newAddress != kyberContract && newAddress != address(0));
kyberContract = newAddress;
}
function setWethContractAddress(
address newAddress)
public
onlyOwner
{
require(newAddress != wethContract && newAddress != address(0));
wethContract = newAddress;
}
function setBZRxTokenContractAddress(
address newAddress)
public
onlyOwner
{
require(newAddress != bZRxTokenContract && newAddress != address(0));
bZRxTokenContract = newAddress;
}
function setEMAValue (
uint _newEMAValue)
public
onlyOwner {
require(_newEMAValue != emaValue);
emaValue = _newEMAValue;
}
function setEMAPeriods (
uint _newEMAPeriods)
public
onlyOwner {
require(_newEMAPeriods > 1 && _newEMAPeriods != emaPeriods);
emaPeriods = _newEMAPeriods;
}
function transferEther(
address to,
uint value)
public
onlyOwner
returns (bool)
{
return (_transferEther(
to,
value
));
}
function transferToken(
address tokenAddress,
address to,
uint value)
public
onlyOwner
returns (bool)
{
return (_transferToken(
tokenAddress,
to,
value
));
}
/*
* Internal functions
*/
function _getEtherFromCollateral(
address collateralTokenAddress,
address loanTokenAddress,
uint collateralTokenAmountUsable,
uint loanTokenAmountNeeded,
bool isLiquidation)
internal
returns (uint etherAmountReceived)
{
uint etherAmountNeeded = 0;
if (loanTokenAmountNeeded > 0) {
if (loanTokenAddress == wethContract) {
etherAmountNeeded = loanTokenAmountNeeded;
} else {
(uint etherToLoan,) = _getExpectedRate(
wethContract,
loanTokenAddress,
0
);
etherAmountNeeded = loanTokenAmountNeeded.mul(_getDecimalPrecision(wethContract, loanTokenAddress)).div(etherToLoan);
}
}
// trade collateral token for ether
etherAmountReceived = _doTradeForEth(
collateralTokenAddress,
collateralTokenAmountUsable,
this, // BZxOracle receives the Ether proceeds
!isLiquidation ? etherAmountNeeded : etherAmountNeeded.add(gasUpperBound.mul(emaValue).mul(bountyRewardPercent).div(100))
);
}
function _getDecimalPrecision(
address sourceToken,
address destToken)
internal
view
returns(uint)
{
uint sourceTokenDecimals = decimals[sourceToken];
if (sourceTokenDecimals == 0)
sourceTokenDecimals = EIP20(sourceToken).decimals();
uint destTokenDecimals = decimals[destToken];
if (destTokenDecimals == 0)
destTokenDecimals = EIP20(destToken).decimals();
if (destTokenDecimals >= sourceTokenDecimals)
return 10**(SafeMath.sub(18, destTokenDecimals-sourceTokenDecimals));
else
return 10**(SafeMath.add(18, sourceTokenDecimals-destTokenDecimals));
}
// ref: https://github.com/KyberNetwork/smart-contracts/blob/master/integration.md#rate-query
function _getExpectedRate(
address sourceTokenAddress,
address destTokenAddress,
uint sourceTokenAmount)
internal
view
returns (uint expectedRate, uint slippageRate)
{
if (sourceTokenAddress == destTokenAddress) {
expectedRate = 10**18;
slippageRate = 0;
} else {
if (sourceTokenAddress == wethContract) {
(expectedRate, slippageRate) = KyberNetwork_Interface(kyberContract).getExpectedRate(
KYBER_ETH_TOKEN_ADDRESS,
destTokenAddress,
sourceTokenAmount
);
} else if (destTokenAddress == wethContract) {
(expectedRate, slippageRate) = KyberNetwork_Interface(kyberContract).getExpectedRate(
sourceTokenAddress,
KYBER_ETH_TOKEN_ADDRESS,
sourceTokenAmount
);
} else {
(uint sourceToEther, uint sourceToEtherSlippage) = KyberNetwork_Interface(kyberContract).getExpectedRate(
sourceTokenAddress,
KYBER_ETH_TOKEN_ADDRESS,
sourceTokenAmount
);
if (sourceTokenAmount > 0) {
sourceTokenAmount = sourceTokenAmount.mul(sourceToEther).div(_getDecimalPrecision(sourceTokenAddress, wethContract));
}
(uint etherToDest, uint etherToDestSlippage) = KyberNetwork_Interface(kyberContract).getExpectedRate(
KYBER_ETH_TOKEN_ADDRESS,
destTokenAddress,
sourceTokenAmount
);
expectedRate = sourceToEther.mul(etherToDest).div(10**18);
slippageRate = sourceToEtherSlippage.mul(etherToDestSlippage).div(10**18);
}
}
}
function _doTrade(
address sourceTokenAddress,
address destTokenAddress,
uint sourceTokenAmount,
uint maxDestTokenAmount)
internal
returns (uint destTokenAmount)
{
if (sourceTokenAddress == destTokenAddress) {
if (maxDestTokenAmount < sourceTokenAmount) {
destTokenAmount = maxDestTokenAmount;
} else {
destTokenAmount = sourceTokenAmount;
}
if (!_transferToken(
destTokenAddress,
vaultContract,
destTokenAmount)) {
revert("BZxOracle::_doTrade: _transferToken failed");
}
} else {
uint tempAllowance = 0;
if (sourceTokenAddress == wethContract) {
WETH_Interface(wethContract).withdraw(sourceTokenAmount);
destTokenAmount = KyberNetwork_Interface(kyberContract).trade
.value(sourceTokenAmount)( // send Ether along
KYBER_ETH_TOKEN_ADDRESS,
sourceTokenAmount,
destTokenAddress,
vaultContract, // bZxVault recieves the destToken
maxDestTokenAmount,
0, // no min coversation rate
address(0)
);
} else if (destTokenAddress == wethContract) {
// re-up the Kyber spend approval if needed
tempAllowance = EIP20(sourceTokenAddress).allowance.gas(4999)(this, kyberContract);
if (tempAllowance < sourceTokenAmount) {
if (tempAllowance > 0) {
// reset approval to 0
eip20Approve(
sourceTokenAddress,
kyberContract,
0);
}
eip20Approve(
sourceTokenAddress,
kyberContract,
MAX_FOR_KYBER);
}
destTokenAmount = KyberNetwork_Interface(kyberContract).trade(
sourceTokenAddress,
sourceTokenAmount,
KYBER_ETH_TOKEN_ADDRESS,
this, // BZxOracle receives the Ether proceeds
maxDestTokenAmount,
0, // no min coversation rate
address(0)
);
WETH_Interface(wethContract).deposit.value(destTokenAmount)();
if (!_transferToken(
destTokenAddress,
vaultContract,
destTokenAmount)) {
revert("BZxOracle::_doTrade: _transferToken failed");
}
} else {
// re-up the Kyber spend approval if needed
tempAllowance = EIP20(sourceTokenAddress).allowance.gas(4999)(this, kyberContract);
if (tempAllowance < sourceTokenAmount) {
if (tempAllowance > 0) {
// reset approval to 0
eip20Approve(
sourceTokenAddress,
kyberContract,
0);
}
eip20Approve(
sourceTokenAddress,
kyberContract,
MAX_FOR_KYBER);
}
uint maxDestEtherAmount = maxDestTokenAmount;
if (maxDestTokenAmount < MAX_FOR_KYBER) {
uint etherToDest;
(etherToDest,) = KyberNetwork_Interface(kyberContract).getExpectedRate(
KYBER_ETH_TOKEN_ADDRESS,
destTokenAddress,
0
);
maxDestEtherAmount = maxDestTokenAmount.mul(_getDecimalPrecision(wethContract, destTokenAddress)).div(etherToDest);
}
uint destEtherAmount = KyberNetwork_Interface(kyberContract).trade(
sourceTokenAddress,
sourceTokenAmount,
KYBER_ETH_TOKEN_ADDRESS,
this, // BZxOracle receives the Ether proceeds
maxDestEtherAmount,
0, // no min coversation rate
address(0)
);
destTokenAmount = KyberNetwork_Interface(kyberContract).trade
.value(destEtherAmount)( // send Ether along
KYBER_ETH_TOKEN_ADDRESS,
destEtherAmount,
destTokenAddress,
vaultContract, // bZxVault recieves the destToken
maxDestTokenAmount,
0, // no min coversation rate
address(0)
);
}
}
}
function _doTradeForEth(
address sourceTokenAddress,
uint sourceTokenAmount,
address receiver,
uint destEthAmountNeeded)
internal
returns (uint destEthAmountReceived)
{
if (sourceTokenAddress == wethContract) {
if (destEthAmountNeeded > sourceTokenAmount)
destEthAmountNeeded = sourceTokenAmount;
WETH_Interface(wethContract).withdraw(destEthAmountNeeded);
if (receiver != address(this)) {
if (!_transferEther(
receiver,
destEthAmountNeeded)) {
revert("BZxOracle::_doTradeForEth: _transferEther failed");
}
}
destEthAmountReceived = destEthAmountNeeded;
} else {
// re-up the Kyber spend approval if needed
uint tempAllowance = EIP20(sourceTokenAddress).allowance.gas(4999)(this, kyberContract);
if (tempAllowance < sourceTokenAmount) {
if (tempAllowance > 0) {
// reset approval to 0
eip20Approve(
sourceTokenAddress,
kyberContract,
0);
}
eip20Approve(
sourceTokenAddress,
kyberContract,
MAX_FOR_KYBER);
}
/* the following code is to allow the Kyber trade to fail silently and not revert if it does, preventing a "bubble up" */
bool result = kyberContract.call(
bytes4(keccak256("trade(address,uint256,address,address,uint256,uint256,address)")),
sourceTokenAddress,
sourceTokenAmount,
KYBER_ETH_TOKEN_ADDRESS,
receiver,
destEthAmountNeeded,
0, // no min coversation rate
address(0)
);
assembly {
switch result
case 0 {
destEthAmountReceived := 0
}
default {
returndatacopy(0, 0, 0x20)
destEthAmountReceived := mload(0)
}
}
}
}
function _doTradeWithEth(
address destTokenAddress,
uint sourceEthAmount,
address receiver,
uint destTokenAmountNeeded)
internal
returns (uint destTokenAmountReceived)
{
if (destTokenAddress == wethContract) {
if (destTokenAmountNeeded > sourceEthAmount)
destTokenAmountNeeded = sourceEthAmount;
if (destTokenAmountNeeded > address(this).balance)
destTokenAmountNeeded = address(this).balance;
WETH_Interface(wethContract).deposit.value(destTokenAmountNeeded)();
if (receiver != address(this)) {
if (!_transferToken(
wethContract,
receiver,
destTokenAmountNeeded)) {
revert("BZxOracle::_doTradeWithEth: _transferToken failed");
}
}
destTokenAmountReceived = destTokenAmountNeeded;
} else {
if (sourceEthAmount >= address(this).balance) {
// only send a little more than needed, rather than the entire contract balance
(uint etherToDest,) = KyberNetwork_Interface(kyberContract).getExpectedRate(
KYBER_ETH_TOKEN_ADDRESS,
destTokenAddress,
0
);
// calculate amount of ETH to use with a 5% buffer (unused ETH is returned by Kyber)
sourceEthAmount = destTokenAmountNeeded.mul(_getDecimalPrecision(wethContract, destTokenAddress)).div(etherToDest).mul(105).div(100);
if (sourceEthAmount > address(this).balance) {
sourceEthAmount = address(this).balance;
}
}
/* the following code is to allow the Kyber trade to fail silently and not revert if it does, preventing a "bubble up" */
bool result = kyberContract.call
.value(sourceEthAmount)( // send Ether along
bytes4(keccak256("trade(address,uint256,address,address,uint256,uint256,address)")),
KYBER_ETH_TOKEN_ADDRESS,
sourceEthAmount,
destTokenAddress,
receiver,
destTokenAmountNeeded,
0, // no min coversation rate
address(0)
);
assembly {
switch result
case 0 {
destTokenAmountReceived := 0
}
default {
returndatacopy(0, 0, 0x20)
destTokenAmountReceived := mload(0)
}
}
}
}
function _transferEther(
address to,
uint value)
internal
returns (bool)
{
uint amount = value;
if (amount > address(this).balance) {
amount = address(this).balance;
}
return (to.send(amount)); // solhint-disable-line check-send-result, multiple-sends
}
function _transferToken(
address tokenAddress,
address to,
uint value)
internal
returns (bool)
{
eip20Transfer(
tokenAddress,
to,
value);
return true;
}
}
| solhint-disable-next-line contract-name-camelcase | interface KyberNetwork_Interface {
function trade(
address src,
uint srcAmount,
address dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
)
external
payable
returns(uint);
function getExpectedRate(
address src,
address dest,
uint srcQty)
external
view
returns (uint expectedRate, uint slippageRate);
}
| 14,071,613 |
./full_match/4/0x29c4264614218D0894502A689b351fa38d42aBE6/sources/ERC721.sol | 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 returns(bool){
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
return true;
}
| 833,019 |
./partial_match/1/0xDC8d77b69155c7E68A95a4fb0f06a71FF90B943a/sources/src/libraries/PendingOwnable.sol | 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 override onlyOwner {
_transferOwnership(address(0));
}
| 3,665,291 |
./full_match/5/0xc40a0656f0EF78bD8eA319C2d2f58587F190e686/sources/contracts/MintBees.sol | metamorphosisURI: Function to get the metadata URI for a bee NFT based on its token ID. This function is public and can be called by anyone. _tokenId uint256 - The token ID of the bee NFT to get the metadata URI for. return string - The metadata URI for the bee NFT. This function gets the metadata URI for a bee NFT based on its token ID. If the token ID is within the first 10,000 IDs minted, it determines the metadata URI based on the current seed value. If the seed value is not set, it returns the base URI for the bee NFTs. If the token ID is not within the first 10,000 IDs minted, it gets the metadata URI from the hive contract using the token ID./ | function getMetamorphosisURI(
uint256 _tokenId
) public view returns (string memory) {
if (_tokenId < stakeSupplyStart) {
if (metadataHash == 0) {
return metamorphosisURI;
return
string(
abi.encodePacked(
metamorphosisURI,
"/",
metamorphosisHash,
"/",
Strings.toString(_tokenId)
)
);
}
return StakedNFTMetadata(hiveContract).getMetadata(_tokenId);
}
}
| 11,599,718 |
./full_match/3/0x505A5362fACFAFefFe2625E7a259266986Aa802c/sources/contracts/IToken_.sol | Sender supplies assets into the market and receives cTokens in exchange Accrues interest whether or not the operation succeeds, unless reverted mintAmount The amount of the underlying asset to supply return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ | function mint(uint mintAmount) external returns (uint) {
return mintInternal(mintAmount, msg.sender, msg.sender);
}
| 8,090,069 |
pragma solidity ^0.4.22;
contract Utils {
function Utils() public {
}
// function compareStrings (string a, string b) view returns (bool){
// return keccak256(a) == keccak256(b);
// }
// // verifies that an amount is greater than zero
// modifier greaterThanZero(uint256 _amount) {
// require(_amount > 0);
// _;
// }
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != address(0));
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
function strlen(string s) internal pure returns (uint) {
// Starting here means the LSB will be the byte we care about
uint ptr;
uint end;
assembly {
ptr := add(s, 1)
end := add(mload(s), ptr)
}
for (uint len = 0; ptr < end; len++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if(b < 0xE0) {
ptr += 2;
} else if(b < 0xF0) {
ptr += 3;
} else if(b < 0xF8) {
ptr += 4;
} else if(b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
return len;
}
}
contract SafeMath {
function SafeMath() {
}
function safeAdd(uint256 _x, uint256 _y) internal returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
function safeSub(uint256 _x, uint256 _y) internal returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
function safeMul(uint256 _x, uint256 _y) internal returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
function safeDiv(uint a, uint b) internal returns (uint256) {
assert(b > 0);
return a / b;
}
}
contract ERC20Interface {
// function totalSupply() public constant returns (uint);
// function balanceOf(address tokenOwner) public constant returns (uint balance);
// function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
/*
Provides support and utilities for contract ownership
*/
contract Owned {
address public owner;
address public newOwner;
event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
/**
@dev constructor
*/
function Owned() public {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
/**
@dev allows transferring the contract ownership
the new owner still needs to accept the transfer
can only be called by the contract owner
@param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
/**
@dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract bundinha is Utils {
uint N;
string bundinha;
function setN(uint x) public {
N = x;
}
function getN() constant public returns (uint) {
return N;
}
function setBundinha(string x) public {
require(strlen(x) <= 32);
bundinha = x;
}
function getBundinha() constant public returns (string){
return bundinha;
}
}
contract SomeCoin is Utils, ERC20Interface, Owned, SafeMath, bundinha {
uint myVariable;
string bundinha;
string public name = '';
string public symbol = '';
uint8 public decimals = 0;
uint256 public totalSupply = 0;
uint256 public maxSupply = 50000000000000000000000;
// 50000.
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Issuance(uint256 _amount);
// function SomeCoin(string _name, string _symbol, uint8 _decimals, uint256 supply) {
function SomeCoin(string _name, string _symbol, uint8 _decimals) {
require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input
name = _name;
symbol = _symbol;
decimals = _decimals;
// totalSupply = supply;
}
function validSupply() private returns(bool) {
return totalSupply <= maxSupply;
}
function transfer(address _to, uint256 _value)
public
validAddress(_to)
returns (bool success)
{
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value)
public
validAddress(_from)
validAddress(_to)
returns (bool success)
{
allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value);
balanceOf[_from] = safeSub(balanceOf[_from], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value)
public
validAddress(_spender)
returns (bool success)
{
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function issue(address _to, uint256 _amount)
public
ownerOnly
validAddress(_to)
notThis(_to)
{
totalSupply = safeAdd(totalSupply, _amount);
balanceOf[_to] = safeAdd(balanceOf[_to], _amount);
require(validSupply());
Issuance(_amount);
Transfer(this, _to, _amount);
}
function transferAnyERC20Token(address _token, address _to, uint256 _amount)
public
ownerOnly
validAddress(_token)
returns (bool success)
{
return ERC20Interface(_token).transfer(_to, _amount);
}
// Don't accept ETH
function () payable {
revert();
}
} | Starting here means the LSB will be the byte we care about | function strlen(string s) internal pure returns (uint) {
uint ptr;
uint end;
assembly {
ptr := add(s, 1)
end := add(mload(s), ptr)
}
for (uint len = 0; ptr < end; len++) {
uint8 b;
if (b < 0x80) {
ptr += 1;
ptr += 2;
ptr += 3;
ptr += 4;
ptr += 5;
ptr += 6;
}
}
return len;
}
| 12,687,255 |
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol";
import "contracts/interface/ICouncil.sol";
import "contracts/interface/IContent.sol";
import "contracts/interface/IContentsManager.sol";
import "contracts/interface/IFundManager.sol";
import "contracts/interface/IAccountManager.sol";
import "contracts/token/CustomToken.sol";
import "contracts/utils/ValidValue.sol";
import "contracts/utils/BytesLib.sol";
contract AccountManager is IAccountManager, ValidValue {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using BytesLib for bytes;
struct Account {
string userName;
string password;
string privateKey;
address wallet;
mapping(address => bool) addressToFavorite;
}
mapping(string => uint256) userNameToIndex;
mapping(address => uint256) addressToIndex;
mapping(string => uint256) privateKeyToIndex;
ICouncil council;
IERC20 token;
Account[] account;
uint256 airdropAmount;
constructor (address _council, uint256 _amount) public {
council = ICouncil(_council);
token = IERC20(council.getToken());
airdropAmount = _amount;
}
/**
* @dev 신규 계정 생성
* @param _userName 계정 이름(ID)
* @param _password 비밀번호
* @param _privateKey 신규로 발급 된 private key
* @param _wallet 신규로 발급 된 public address
*/
function createNewAccount(
string _userName,
string _password,
string _privateKey,
address _wallet
)
external
validAddress(_wallet) validString(_userName)
validString(_password) validString(_privateKey)
{
require(!isRegisteredUserName(_userName), "Create new account failed: Registered user name.");
require(!isRegisteredPrivateKey(_privateKey), "Create new account failed: Registered user private key.");
require(!isRegisteredWallet(_wallet), "Create new account failed: Registered user wallet address.");
account.push(Account(_userName, _password, _privateKey, _wallet));
userNameToIndex[_userName] = account.length.sub(1);
addressToIndex[_wallet] = account.length.sub(1);
privateKeyToIndex[_privateKey] = account.length.sub(1);
if (airdropAmount > 0 && token.balanceOf(address(this)) >= airdropAmount) {
CustomToken(address(token)).transferPxl(msg.sender, airdropAmount, "에어드롭 픽셀 입금");
}
emit RegisterNewAccount(account.length.sub(1), _wallet, _userName);
}
/**
* @dev 로그인 처리
* @param _userName 계정 이름(ID)
* @param _password 비밀번호
* @return key_ 로그인 성공 시 private key 전달, 실패시 에러 메시지 전달
* @return result_ 로그인 성공 여부
*/
function login(
string _userName,
string _password
)
external
view
validString(_userName) validString(_userName)
returns (string key_, bool result_)
{
if(account.length == 0 || !isRegisteredUserName(_userName)) {
key_ = "Login failed: Please register account.";
result_ = false;
return;
}
if(!_compareString(account[userNameToIndex[_userName]].password, _password)) {
key_ = "Login failed: check register account.";
result_ = false;
return;
}
key_ = account[userNameToIndex[_userName]].privateKey;
result_ = true;
}
/**
* @dev 구매 내역 이벤트 처리
* @param _buyer 구매자 주소
* @param _contentsAddress 구매한 컨텐츠 컨트랙트 주소
* @param _episodeIndex 구매한 컨텐츠 컨트랙트 주소
* @param _episodePrice 구매한 컨텐츠 컨트랙트 주소
*/
function setPurchaseHistory(
address _buyer,
address _contentsAddress,
uint256 _episodeIndex,
uint256 _episodePrice
)
external
validAddress(_contentsAddress) validAddress(_buyer)
{
require(council.getPixelDistributor() == msg.sender, "Purchase failed: Access denied.");
require(isRegisteredWallet(_buyer), "Purchase failed: Please register account.");
emit PurchaseHistory(_buyer, _contentsAddress, _episodeIndex, _episodePrice);
}
/**
* @dev 사용자 비밀번호 변경
* @param _newPassword 변경할 비밀번호
* @param _passwordValidation 비밀번호 문자열 확인
*/
function setNewPassword(
string _newPassword,
string _passwordValidation
)
external
validString(_newPassword) validString(_passwordValidation)
{
require(isRegisteredWallet(msg.sender), "Set new password falid : Please register account.");
require(_compareString(_newPassword, _passwordValidation), "Set new password falid : Check password string.");
account[addressToIndex[msg.sender]].password = _newPassword;
}
/**
* @dev 투자 내역 저장
* @param _supporter 투자자 주소
* @param _contentsAddress 투자한 작품 주소
* @param _fundAddress fund contract 주소
* @param _investedAmount 투자 금액
* @param _refund 환불 여부
*/
function setSupportHistory(
address _supporter,
address _contentsAddress,
address _fundAddress,
uint256 _investedAmount,
bool _refund
)
external
validAddress(_supporter) validAddress(_fundAddress) validAddress(_contentsAddress)
{
require(_isFundContract(_fundAddress, _contentsAddress), "Support history failed: Invalid address.");
require(isRegisteredWallet(_supporter), "Support history failed: Please register account.");
emit SupportHistory(_supporter, _contentsAddress, _fundAddress, _investedAmount, _refund);
}
function changeFavoriteContent(
address _user,
address _contentAddress
)
external
validAddress(_contentAddress) validAddress(_user)
{
require(_isContentContract(_contentAddress), "Change favorite content failed: Invalid content address.");
require(isRegisteredWallet(_user), "Change favorite content failed: Please register account.");
if(account[addressToIndex[_user]].addressToFavorite[_contentAddress]) {
account[addressToIndex[_user]].addressToFavorite[_contentAddress] = false;
} else {
account[addressToIndex[_user]].addressToFavorite[_contentAddress] = true;
}
}
function getFavoriteContent(
address _user,
address _contentAddress
)
external
view
returns (bool isFavoriteContent_)
{
isFavoriteContent_ = account[addressToIndex[_user]].addressToFavorite[_contentAddress];
}
/**
* @dev 등록 된 ID인지 확인
* @param _userName 유저 ID
* @return isRegistered_ 등록 여부
*/
function isRegisteredUserName(
string _userName
)
public
view
validString(_userName)
returns (bool isRegistered_)
{
if(userNameToIndex[_userName] > 0) {
isRegistered_ = true;
return;
}
if(account.length > 0 && userNameToIndex[_userName] == 0 && _compareString(account[userNameToIndex[_userName]].userName, _userName)) {
isRegistered_ = true;
return;
}
}
/**
* @dev 등록 된 지갑 주소인지 확인
* @param _wallet 유저 지갑 주소
* @return isRegistered_ 등록 여부
*/
function isRegisteredWallet(
address _wallet
)
public
view
validAddress(_wallet)
returns (bool isRegistered_)
{
if(addressToIndex[_wallet] > 0) {
isRegistered_ = true;
return;
}
if(account.length > 0 && addressToIndex[_wallet] == 0 && account[addressToIndex[_wallet]].wallet == _wallet) {
isRegistered_ = true;
return;
}
}
/**
* @dev 등록 된 인증키 인지 확인
* @param _privateKey 유저 private key
* @return isRegistered_ 등록 여부
*/
function isRegisteredPrivateKey(
string _privateKey
)
public
view
validString(_privateKey)
returns (bool isRegistered_)
{
if(privateKeyToIndex[_privateKey] > 0) {
isRegistered_ = true;
return;
}
if(account.length > 0 && privateKeyToIndex[_privateKey] == 0
&& _compareString(account[privateKeyToIndex[_privateKey]].privateKey, _privateKey)) {
isRegistered_ = true;
return;
}
}
/**
* @dev ID 조회
* @param _wallet 계정의 지갑 주소
* @return userName_ ID
* @return result_ 조회 결과
*/
function getUserName(
address _wallet
)
external
view
validAddress(_wallet)
returns (string memory userName_, bool result_)
{
if(account.length > 0 && account[addressToIndex[_wallet]].wallet == _wallet) {
userName_ = account[addressToIndex[_wallet]].userName;
result_ = true;
}
}
/**
* @dev ID 조회
* @param _wallet 계정의 지갑 주소 배열
* @return writer_ 유저 주소
* @return writerName_ bytes로 변환한 유저 이름
* @return spos_ bytes로 변환 된 writerName_의 start index
* @return epos_ bytes로 변환 된 writerName_의 end index
*/
function getUserNames(
address[] _wallet
)
external
view
returns (address[] memory writer_, bytes memory writerName_, uint256[] memory spos_, uint256[] memory epos_)
{
uint256 writerNameLength = _wallet.length;
writer_ = _wallet;
spos_ = new uint256[](writerNameLength);
epos_ = new uint256[](writerNameLength);
uint256 tempLength;
for(uint256 i = 0 ; i < writerNameLength ; i++) {
bytes memory str = bytes(account[addressToIndex[writer_[i]]].userName);
spos_[i] = tempLength;
writerName_ = writerName_.concat(str);
tempLength = (tempLength == 0)? tempLength.add((str.length).mul(2).add(2)) : tempLength.add((str.length).mul(2));
epos_[i] = tempLength;
}
}
function _isFundContract(
address _fundAddress,
address _contentsAddress
)
private
view
returns (bool isFundContract_)
{
address fundAddress = IFundManager(council.getFundManager()).getFund(_contentsAddress);
isFundContract_ = (fundAddress == _fundAddress);
}
function _isContentContract(
address _contentsAddress
)
private
view
returns (bool isContentContract_)
{
address[] memory contentsAddress = IContentsManager(council.getContentsManager()).getContentsAddress();
if(contentsAddress.length == 0) {
return;
}
for(uint256 i = 0 ; i < contentsAddress.length ; i++){
if(contentsAddress[i] == _contentsAddress) {
isContentContract_ = true;
break;
}
}
}
function _compareString(
string _a,
string _b
)
private
pure
returns (bool)
{
return keccak256(_a) == keccak256(_b);
}
}
| 로그인 처리 _userName 계정 이름(ID) _password 비밀번호 return key_ 로그인 성공 시 private key 전달, 실패시 에러 메시지 전달 return result_ 로그인 성공 여부/ | function login(
string _userName,
string _password
)
external
view
validString(_userName) validString(_userName)
returns (string key_, bool result_)
{
if(account.length == 0 || !isRegisteredUserName(_userName)) {
key_ = "Login failed: Please register account.";
result_ = false;
return;
}
if(!_compareString(account[userNameToIndex[_userName]].password, _password)) {
key_ = "Login failed: check register account.";
result_ = false;
return;
}
key_ = account[userNameToIndex[_userName]].privateKey;
result_ = true;
}
| 12,893,319 |
pragma solidity 0.6.12;
// COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/CarefulMath.sol
//Copyright 2020 Compound Labs, Inc.
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
// COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/Exponential.sol
//Copyright 2020 Compound Labs, Inc.
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
// COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/ComptrollerInterface.sol
//Copyright 2020 Compound Labs, Inc.
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
interface IComptroller {
/*** Assets You Are In ***/
/**
* PIGGY-MODIFY:
* @notice Add assets to be included in account liquidity calculation
* @param pTokens The list of addresses of the cToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] calldata pTokens) external returns (uint[] memory);
/**
* PIGGY-MODIFY:
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param pTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address pTokenAddress) external returns (uint);
/*** Policy Hooks ***/
/**
* PIGGY-MODIFY:
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param pToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(
address pToken,
address minter,
uint mintAmount
) external returns (uint);
/**
* PIGGY-MODIFY:
* @notice Validates mint and reverts on rejection. May emit logs.
* @param pToken Asset being minted
* @param minter The address minting the tokens
* @param mintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(
address pToken,
address minter,
uint mintAmount,
uint mintTokens
) external;
/**
* PIGGY-MODIFY:
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param pToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of cTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(
address pToken,
address redeemer,
uint redeemTokens
) external returns (uint);
/**
* PIGGY-MODIFY:
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param pToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(
address pToken,
address redeemer,
uint redeemAmount,
uint redeemTokens
) external;
/**
* PIGGY-MODIFY:
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param pToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(
address pToken,
address borrower,
uint borrowAmount
) external returns (uint);
/**
* PIGGY-MODIFY:
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param pToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(
address pToken,
address borrower,
uint borrowAmount
) external;
/**
* PIGGY-MODIFY:
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param pToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address pToken,
address payer,
address borrower,
uint repayAmount
) external returns (uint);
/**
* PIGGY-MODIFY:
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param pToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address pToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex
) external;
/**
* PIGGY-MODIFY:
* @notice Checks if the liquidation should be allowed to occur
* @param pTokenBorrowed Asset which was borrowed by the borrower
* @param pTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address pTokenBorrowed,
address pTokenCollateral,
address liquidator,
address borrower,
uint repayAmount
) external returns (uint);
/**
* PIGGY-MODIFY:
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param pTokenBorrowed Asset which was borrowed by the borrower
* @param pTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address pTokenBorrowed,
address pTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens
) external;
/**
* PIGGY-MODIFY:
* @notice Checks if the seizing of assets should be allowed to occur
* @param pTokenCollateral Asset which was used as collateral and will be seized
* @param pTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address pTokenCollateral,
address pTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens
) external returns (uint);
/**
* PIGGY-MODIFY:
* @notice Validates seize and reverts on rejection. May emit logs.
* @param pTokenCollateral Asset which was used as collateral and will be seized
* @param pTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address pTokenCollateral,
address pTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens
) external;
/**
* PIGGY-MODIFY:
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param pToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of pTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(
address pToken,
address src,
address dst,
uint transferTokens
) external returns (uint);
/**
* PIGGY-MODIFY:
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param pToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of pTokens to transfer
*/
function transferVerify(
address pToken,
address src,
address dst,
uint transferTokens
) external;
/*** Liquidity/Liquidation Calculations ***/
/**
* PIGGY-MODIFY:
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in cToken.liquidateBorrowFresh)
* @param pTokenBorrowed The address of the borrowed cToken
* @param pTokenCollateral The address of the collateral cToken
* @param repayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens
* @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(
address pTokenBorrowed,
address pTokenCollateral,
uint repayAmount
) external view returns (uint, uint);
}
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/InterestRateModel.sol
//Copyright 2020 Compound Labs, Inc.
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @title wepiggy's IInterestRateModel Interface
* @author wepiggy
*/
interface IInterestRateModel {
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol
//Copyright 2020 Compound Labs, Inc.
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
contract PTokenStorage {
/**
* @notice Indicator that this is a PToken contract (for inspection)
*/
bool public constant isPToken = true;
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @dev
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @dev
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @dev
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @dev
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint256 internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @dev
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint256 internal constant reserveFactorMaxMantissa = 1e18;
/**
* @dev
* @notice Contract which oversees inter-pToken operations
*/
IComptroller public comptroller;
/**
* @dev
* @notice Model which tells what the current interest rate should be
*/
IInterestRateModel public interestRateModel;
/**
* @dev
* @notice Initial exchange rate used when minting the first PTokens (used when totalSupply = 0)
*/
uint256 internal initialExchangeRateMantissa;
/**
* @dev
* @notice Fraction of interest currently set aside for reserves
*/
uint256 public reserveFactorMantissa;
/**
* @dev
* @notice Block number that interest was last accrued at
*/
uint256 public accrualBlockNumber;
/**
* @dev
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint256 public borrowIndex;
/**
* @dev
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint256 public totalBorrows;
/**
* @dev
* @notice Total amount of reserves of the underlying held in this market
*/
uint256 public totalReserves;
/**
* @dev
* @notice Total number of tokens in circulation
*/
uint256 public totalSupply;
/**
* @dev
* @notice Official record of token balances for each account
*/
mapping(address => uint256) internal accountTokens;
/**
* @dev
* @notice Approved token transfer amounts on behalf of others
*/
mapping(address => mapping(address => uint256)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint256 principal;
uint256 interestIndex;
}
/**
* @dev
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
address public migrator;
uint256 public minInterestAccumulated;
}
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol
//Copyright 2020 Compound Labs, Inc.
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
abstract contract IPToken is PTokenStorage {
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows, uint256 totalReserves);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint256 mintAmount, uint256 mintTokens, uint256 totalSupply, uint256 accountTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens, uint256 totalSupply, uint256 accountTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows, uint256 interestBalancePrior);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows, uint256 interestBalancePrior);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint256 repayAmount, address pTokenCollateral, uint256 seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when comptroller is changed
*/
event NewComptroller(IComptroller oldComptroller, IComptroller newComptroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(IInterestRateModel oldInterestRateModel, IInterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint256 amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Failure event
*/
event Failure(uint256 error, uint256 info, uint256 detail);
event NewMigrator(address oldMigrator, address newMigrator);
event NewMinInterestAccumulated(uint256 oldMinInterestAccumulated, uint256 newMinInterestAccumulated);
/*** User Interface ***/
function transfer(address dst, uint256 amount) external virtual returns (bool);
function transferFrom(address src, address dst, uint256 amount) external virtual returns (bool);
function approve(address spender, uint256 amount) external virtual returns (bool);
function allowance(address owner, address spender) external virtual view returns (uint256);
function balanceOf(address owner) external virtual view returns (uint256);
function balanceOfUnderlying(address owner) external virtual returns (uint256);
function getAccountSnapshot(address account) external virtual view returns (uint256, uint256, uint256, uint256);
function borrowRatePerBlock() external virtual view returns (uint256);
function supplyRatePerBlock() external virtual view returns (uint256);
function totalBorrowsCurrent() external virtual returns (uint256);
function borrowBalanceCurrent(address account) external virtual returns (uint256);
function borrowBalanceStored(address account) public virtual view returns (uint256);
function exchangeRateCurrent() public virtual returns (uint256);
function exchangeRateStored() public virtual view returns (uint256);
function getCash() external virtual view returns (uint256);
function accrueInterest() public virtual returns (uint256);
function seize(address liquidator, address borrower, uint256 seizeTokens) external virtual returns (uint256);
/*** Admin Functions ***/
function _setComptroller(IComptroller newComptroller) public virtual returns (uint256);
function _setReserveFactor(uint256 newReserveFactorMantissa) external virtual returns (uint256);
function _reduceReserves(uint256 reduceAmount) external virtual returns (uint256);
function _setInterestRateModel(IInterestRateModel newInterestRateModel) public virtual returns (uint256);
function _setMigrator(address newMigrator) public virtual returns (uint256);
function _setMinInterestAccumulated(uint _minInterestAccumulated) public virtual returns (uint256);
}
// COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/ErrorReporter.sol
//Copyright 2020 Compound Labs, Inc.
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
COMPTROLLER_REJECTION,
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_INTEREST_BALANCE_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_COMPTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_INTEREST_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
/**
* @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;
}
/*
* @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;
}
/**
* @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;
}
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/CToken.sol
//Copyright 2020 Compound Labs, Inc.
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @title WePiggy's PToken Contract
* @notice Abstract base for PTokens
* @author Compound
*/
abstract contract PToken is IPToken, Exponential, TokenErrorReporter, OwnableUpgradeSafe {
/**
* @notice Initialize the money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function init(IComptroller comptroller_,
IInterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public onlyOwner {
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(- 1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(- 1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external override nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external override nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external override returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external override view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @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 override view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external override returns (uint) {
Exp memory exchangeRate = Exp({mantissa : exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external override view returns (uint, uint, uint, uint) {
uint cTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external override view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external override view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external override nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external override nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public override view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Return the borrow interest balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowInterestBalancePriorInternal(address account) internal view returns (MathError, uint) {
MathError mathErr;
uint interestTimesIndex;
uint principalTimesIndex;
uint interestAmountPrior;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
(mathErr, interestTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
if (borrowSnapshot.interestIndex == 0) {
return (MathError.NO_ERROR, 0);
}
(mathErr, principalTimesIndex) = divUInt(interestTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, interestAmountPrior) = subUInt(principalTimesIndex, borrowSnapshot.principal);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, interestAmountPrior);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public override nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @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() public override view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external override view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This function is copy form accrueInterest.
*/
function accrueInterestSnapshot() public view returns (uint[] memory) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
uint[] memory res = new uint[](6);
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa : borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return res;
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return res;
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return res;
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa : reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return res;
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return res;
}
res[0] = currentBlockNumber;
res[1] = cashPrior;
res[2] = interestAccumulated;
res[3] = totalBorrowsNew;
res[4] = totalReservesNew;
res[5] = borrowIndexNew;
return res;
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public override returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa : borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
// if interestAccumulated < minInterestAccumulated, set interestAccumulated = minInterestAccumulated
(mathErr,) = subUInt(interestAccumulated, minInterestAccumulated);
if (mathErr != MathError.NO_ERROR) {
interestAccumulated = minInterestAccumulated;
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa : reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount, 0);
}
function mintInternalForMigrate(uint mintAmount, uint mintTokens) internal nonReentrant returns (uint, uint) {
require(msg.sender == migrator, "mintInternalForMigrate: caller is not the migrator");
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount, mintTokens);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount, uint mintTokens) internal returns (uint, uint) {
/* Fail if mint not allowed */
if (mintTokens == 0) {
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
if (mintTokens == 0) {
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
if (mintTokens == 0) {
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa : vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
} else {
vars.mintTokens = mintTokens;
}
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens, vars.totalSupplyNew, vars.accountTokensNew);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @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 a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa : vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa : vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens, vars.totalSupplyNew, vars.accountTokensNew);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint interestBalancePrior; //interest balance before now.
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.interestBalancePrior) = borrowInterestBalancePriorInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_INTEREST_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew, vars.interestBalancePrior);
/* We call the defense hook */
comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
uint interestBalancePrior;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
(vars.mathErr, vars.interestBalancePrior) = borrowInterestBalancePriorInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_INTEREST_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(- 1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew, vars.interestBalancePrior);
/* We call the defense hook */
comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param pTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, IPToken pTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = pTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, pTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param pTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, IPToken pTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(pTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify pTokenCollateral market's block number equals current block number */
if (pTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(- 1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(pTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(pTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(pTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = pTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(pTokenCollateral), seizeTokens);
/* We call the defense hook */
comptroller.liquidateBorrowVerify(address(this), address(pTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external override nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(IComptroller newComptroller) public onlyOwner override returns (uint) {
IComptroller oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
// require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external override nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal onlyOwner returns (uint) {
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error,) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external override nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal onlyOwner returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(payable(owner()), reduceAmount);
emit ReservesReduced(owner(), reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(IInterestRateModel newInterestRateModel) public override returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(IInterestRateModel newInterestRateModel) internal onlyOwner returns (uint) {
// Used to store old model for use in the event that is emitted on success
IInterestRateModel oldInterestRateModel;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
// require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
function _setMigrator(address newMigrator) public onlyOwner override returns (uint) {
address oldMigrator = migrator;
// Set market's comptroller to newComptroller
migrator = newMigrator;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewMigrator(oldMigrator, newMigrator);
return uint(Error.NO_ERROR);
}
function _setMinInterestAccumulated(uint _minInterestAccumulated) public onlyOwner override returns (uint256){
uint oldMinInterestAccumulated = minInterestAccumulated;
minInterestAccumulated = _minInterestAccumulated;
emit NewMinInterestAccumulated(oldMinInterestAccumulated, _minInterestAccumulated);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal virtual view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal virtual returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal virtual;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true;
// get a gas-refund post-Istanbul
}
}
/**
* @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);
}
// COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/PriceOracle.sol
//Copyright 2020 Compound Labs, Inc.
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
interface IPriceOracle {
/**
* @notice Get the underlying price of a asset
* @param _pToken The asset to get the underlying price of
* @return The underlying asset price.
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(PToken _pToken) external view returns (uint);
}
// COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/ComptrollerStorage.sol
//Copyright 2020 Compound Labs, Inc.
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
contract ComptrollerStorage {
//PIGGY-MODIFY:Copy and modify from ComptrollerV1Storage
/**
* @notice Oracle which gives the price of any given asset
*/
IPriceOracle public oracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint256 public closeFactorMantissa;
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint256 public liquidationIncentiveMantissa;
/**
* @notice Max number of assets a single account can participate in (borrow or use as collateral)
*/
uint256 public maxAssets;
/**
* PIGGY-MODIFY:
* @notice Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => PToken[]) public accountAssets;
/**
* PIGGY-MODIFY: Copy and modify from ComptrollerV2Storage
*/
struct Market {
// @notice Whether or not this market is listed
bool isListed;
// @notice Multiplier representing the most one can borrow against their collateral in this market.
// For instance, 0.9 to allow borrowing 90% of collateral value. Must be between 0 and 1, and stored as a mantissa.
uint256 collateralFactorMantissa;
// @notice Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
// @notice Whether or not this market receives WPC
bool isMinted;
}
/**
* @notice Official mapping of pTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/**
* @notice The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public pTokenMintGuardianPaused;
mapping(address => bool) public pTokenBorrowGuardianPaused;
bool public distributeWpcPaused;
//PIGGY-MODIFY: Copy and modify from ComptrollerV4Storage
// @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market.
address public borrowCapGuardian;
// @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing.
mapping(address => uint256) public borrowCaps;
//PIGGY-MODIFY: Copy and modify from ComptrollerV3Storage
/// @notice A list of all markets
PToken[] public allMarkets;
}
interface IPiggyDistribution {
function distributeMintWpc(address pToken, address minter, bool distributeAll) external;
function distributeRedeemWpc(address pToken, address redeemer, bool distributeAll) external;
function distributeBorrowWpc(address pToken, address borrower, bool distributeAll) external;
function distributeRepayBorrowWpc(address pToken, address borrower, bool distributeAll) external;
function distributeSeizeWpc(address pTokenCollateral, address borrower, address liquidator, bool distributeAll) external;
function distributeTransferWpc(address pToken, address src, address dst, bool distributeAll) external;
}
interface IPiggyBreeder {
function stake(uint256 _pid, uint256 _amount) external;
function unStake(uint256 _pid, uint256 _amount) external;
function claim(uint256 _pid) external;
function emergencyWithdraw(uint256 _pid) external;
}
contract PiggyDistribution is IPiggyDistribution, Exponential, OwnableUpgradeSafe {
IERC20 public piggy;
IPiggyBreeder public piggyBreeder;
Comptroller public comptroller;
//PIGGY-MODIFY: Copy and modify from ComptrollerV3Storage
struct WpcMarketState {
/// @notice The market's last updated compBorrowIndex or compSupplyIndex
uint224 index;
/// @notice The block number the index was last updated at
uint32 block;
}
/// @notice The portion of compRate that each market currently receives
mapping(address => uint) public wpcSpeeds;
/// @notice The WPC market supply state for each market
mapping(address => WpcMarketState) public wpcSupplyState;
/// @notice The WPC market borrow state for each market
mapping(address => WpcMarketState) public wpcBorrowState;
/// @notice The WPC borrow index for each market for each supplier as of the last time they accrued WPC
mapping(address => mapping(address => uint)) public wpcSupplierIndex;
/// @notice The WPC borrow index for each market for each borrower as of the last time they accrued WPC
mapping(address => mapping(address => uint)) public wpcBorrowerIndex;
/// @notice The WPC accrued but not yet transferred to each user
mapping(address => uint) public wpcAccrued;
/// @notice The threshold above which the flywheel transfers WPC, in wei
uint public constant wpcClaimThreshold = 0.001e18;
/// @notice The initial WPC index for a market
uint224 public constant wpcInitialIndex = 1e36;
bool public enableWpcClaim;
bool public enableDistributeMintWpc;
bool public enableDistributeRedeemWpc;
bool public enableDistributeBorrowWpc;
bool public enableDistributeRepayBorrowWpc;
bool public enableDistributeSeizeWpc;
bool public enableDistributeTransferWpc;
/// @notice Emitted when a new WPC speed is calculated for a market
event WpcSpeedUpdated(PToken indexed pToken, uint newSpeed);
/// @notice Emitted when WPC is distributed to a supplier
event DistributedSupplierWpc(PToken indexed pToken, address indexed supplier, uint wpcDelta, uint wpcSupplyIndex);
/// @notice Emitted when WPC is distributed to a borrower
event DistributedBorrowerWpc(PToken indexed pToken, address indexed borrower, uint wpcDelta, uint wpcBorrowIndex);
event StakeTokenToPiggyBreeder(IERC20 token, uint pid, uint amount);
event ClaimWpcFromPiggyBreeder(uint pid);
event EnableState(string action, bool state);
function initialize(IERC20 _piggy, IPiggyBreeder _piggyBreeder, Comptroller _comptroller) public initializer {
piggy = _piggy;
piggyBreeder = _piggyBreeder;
comptroller = _comptroller;
enableWpcClaim = false;
enableDistributeMintWpc = false;
enableDistributeRedeemWpc = false;
enableDistributeBorrowWpc = false;
enableDistributeRepayBorrowWpc = false;
enableDistributeSeizeWpc = false;
enableDistributeTransferWpc = false;
super.__Ownable_init();
}
function distributeMintWpc(address pToken, address minter, bool distributeAll) public override(IPiggyDistribution) {
require(msg.sender == address(comptroller) || msg.sender == owner(), "only comptroller or owner");
if (enableDistributeMintWpc) {
updateWpcSupplyIndex(pToken);
distributeSupplierWpc(pToken, minter, distributeAll);
}
}
function distributeRedeemWpc(address pToken, address redeemer, bool distributeAll) public override(IPiggyDistribution) {
require(msg.sender == address(comptroller) || msg.sender == owner(), "only comptroller or owner");
if (enableDistributeRedeemWpc) {
updateWpcSupplyIndex(pToken);
distributeSupplierWpc(pToken, redeemer, distributeAll);
}
}
function distributeBorrowWpc(address pToken, address borrower, bool distributeAll) public override(IPiggyDistribution) {
require(msg.sender == address(comptroller) || msg.sender == owner(), "only comptroller or owner");
if (enableDistributeBorrowWpc) {
Exp memory borrowIndex = Exp({mantissa : PToken(pToken).borrowIndex()});
updateWpcBorrowIndex(pToken, borrowIndex);
distributeBorrowerWpc(pToken, borrower, borrowIndex, distributeAll);
}
}
function distributeRepayBorrowWpc(address pToken, address borrower, bool distributeAll) public override(IPiggyDistribution) {
require(msg.sender == address(comptroller) || msg.sender == owner(), "only comptroller or owner");
if (enableDistributeRepayBorrowWpc) {
Exp memory borrowIndex = Exp({mantissa : PToken(pToken).borrowIndex()});
updateWpcBorrowIndex(pToken, borrowIndex);
distributeBorrowerWpc(pToken, borrower, borrowIndex, distributeAll);
}
}
function distributeSeizeWpc(address pTokenCollateral, address borrower, address liquidator, bool distributeAll) public override(IPiggyDistribution) {
require(msg.sender == address(comptroller) || msg.sender == owner(), "only comptroller or owner");
if (enableDistributeSeizeWpc) {
updateWpcSupplyIndex(pTokenCollateral);
distributeSupplierWpc(pTokenCollateral, borrower, distributeAll);
distributeSupplierWpc(pTokenCollateral, liquidator, distributeAll);
}
}
function distributeTransferWpc(address pToken, address src, address dst, bool distributeAll) public override(IPiggyDistribution) {
require(msg.sender == address(comptroller) || msg.sender == owner(), "only comptroller or owner");
if (enableDistributeTransferWpc) {
updateWpcSupplyIndex(pToken);
distributeSupplierWpc(pToken, src, distributeAll);
distributeSupplierWpc(pToken, dst, distributeAll);
}
}
function _stakeTokenToPiggyBreeder(IERC20 token, uint pid) public onlyOwner {
uint amount = token.balanceOf(address(this));
token.approve(address(piggyBreeder), amount);
piggyBreeder.stake(pid, amount);
emit StakeTokenToPiggyBreeder(token, pid, amount);
}
function _claimWpcFromPiggyBreeder(uint pid) public onlyOwner {
piggyBreeder.claim(pid);
emit ClaimWpcFromPiggyBreeder(pid);
}
function setWpcSpeedInternal(PToken pToken, uint wpcSpeed) internal {
uint currentWpcSpeed = wpcSpeeds[address(pToken)];
if (currentWpcSpeed != 0) {
// note that WPC speed could be set to 0 to halt liquidity rewards for a market
Exp memory borrowIndex = Exp({mantissa : pToken.borrowIndex()});
updateWpcSupplyIndex(address(pToken));
updateWpcBorrowIndex(address(pToken), borrowIndex);
} else if (wpcSpeed != 0) {
require(comptroller.isMarketListed(address(pToken)), "wpc market is not listed");
if (comptroller.isMarketMinted(address(pToken)) == false) {
comptroller._setMarketMinted(address(pToken), true);
}
if (wpcSupplyState[address(pToken)].index == 0 && wpcSupplyState[address(pToken)].block == 0) {
wpcSupplyState[address(pToken)] = WpcMarketState({
index : wpcInitialIndex,
block : safe32(block.number, "block number exceeds 32 bits")
});
}
if (wpcBorrowState[address(pToken)].index == 0 && wpcBorrowState[address(pToken)].block == 0) {
wpcBorrowState[address(pToken)] = WpcMarketState({
index : wpcInitialIndex,
block : safe32(block.number, "block number exceeds 32 bits")
});
}
}
if (currentWpcSpeed != wpcSpeed) {
wpcSpeeds[address(pToken)] = wpcSpeed;
emit WpcSpeedUpdated(pToken, wpcSpeed);
}
}
/**
* @notice Accrue WPC to the market by updating the supply index
* @param pToken The market whose supply index to update
*/
function updateWpcSupplyIndex(address pToken) internal {
WpcMarketState storage supplyState = wpcSupplyState[pToken];
uint supplySpeed = wpcSpeeds[pToken];
uint blockNumber = block.number;
uint deltaBlocks = sub_(blockNumber, uint(supplyState.block));
if (deltaBlocks > 0 && supplySpeed > 0) {
uint supplyTokens = PToken(pToken).totalSupply();
uint wpcAccrued = mul_(deltaBlocks, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(wpcAccrued, supplyTokens) : Double({mantissa : 0});
Double memory index = add_(Double({mantissa : supplyState.index}), ratio);
wpcSupplyState[pToken] = WpcMarketState({
index : safe224(index.mantissa, "new index exceeds 224 bits"),
block : safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
supplyState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Accrue WPC to the market by updating the borrow index
* @param pToken The market whose borrow index to update
*/
function updateWpcBorrowIndex(address pToken, Exp memory marketBorrowIndex) internal {
WpcMarketState storage borrowState = wpcBorrowState[pToken];
uint borrowSpeed = wpcSpeeds[pToken];
uint blockNumber = block.number;
uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));
if (deltaBlocks > 0 && borrowSpeed > 0) {
uint borrowAmount = div_(PToken(pToken).totalBorrows(), marketBorrowIndex);
uint wpcAccrued = mul_(deltaBlocks, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(wpcAccrued, borrowAmount) : Double({mantissa : 0});
Double memory index = add_(Double({mantissa : borrowState.index}), ratio);
wpcBorrowState[pToken] = WpcMarketState({
index : safe224(index.mantissa, "new index exceeds 224 bits"),
block : safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Calculate WPC accrued by a supplier and possibly transfer it to them
* @param pToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute WPC to
*/
function distributeSupplierWpc(address pToken, address supplier, bool distributeAll) internal {
WpcMarketState storage supplyState = wpcSupplyState[pToken];
Double memory supplyIndex = Double({mantissa : supplyState.index});
Double memory supplierIndex = Double({mantissa : wpcSupplierIndex[pToken][supplier]});
wpcSupplierIndex[pToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = wpcInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = PToken(pToken).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
uint supplierAccrued = add_(wpcAccrued[supplier], supplierDelta);
wpcAccrued[supplier] = grantWpcInternal(supplier, supplierAccrued, distributeAll ? 0 : wpcClaimThreshold);
emit DistributedSupplierWpc(PToken(pToken), supplier, supplierDelta, supplyIndex.mantissa);
}
/**
* @notice Calculate WPC accrued by a borrower and possibly transfer it to them
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param pToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute WPC to
*/
function distributeBorrowerWpc(address pToken, address borrower, Exp memory marketBorrowIndex, bool distributeAll) internal {
WpcMarketState storage borrowState = wpcBorrowState[pToken];
Double memory borrowIndex = Double({mantissa : borrowState.index});
Double memory borrowerIndex = Double({mantissa : wpcBorrowerIndex[pToken][borrower]});
wpcBorrowerIndex[pToken][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(PToken(pToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint borrowerAccrued = add_(wpcAccrued[borrower], borrowerDelta);
wpcAccrued[borrower] = grantWpcInternal(borrower, borrowerAccrued, distributeAll ? 0 : wpcClaimThreshold);
emit DistributedBorrowerWpc(PToken(pToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Transfer WPC to the user, if they are above the threshold
* @dev Note: If there is not enough WPC, we do not perform the transfer all.
* @param user The address of the user to transfer WPC to
* @param userAccrued The amount of WPC to (possibly) transfer
* @return The amount of WPC which was NOT transferred to the user
*/
function grantWpcInternal(address user, uint userAccrued, uint threshold) internal returns (uint) {
if (userAccrued >= threshold && userAccrued > 0) {
uint wpcRemaining = piggy.balanceOf(address(this));
if (userAccrued <= wpcRemaining) {
piggy.transfer(user, userAccrued);
return 0;
}
}
return userAccrued;
}
/**
* @notice Claim all the wpc accrued by holder in all markets
* @param holder The address to claim WPC for
*/
function claimWpc(address holder) public {
claimWpc(holder, comptroller.getAllMarkets());
}
/**
* @notice Claim all the comp accrued by holder in the specified markets
* @param holder The address to claim WPC for
* @param pTokens The list of markets to claim WPC in
*/
function claimWpc(address holder, PToken[] memory pTokens) public {
address[] memory holders = new address[](1);
holders[0] = holder;
claimWpc(holders, pTokens, true, false);
}
/**
* @notice Claim all wpc accrued by the holders
* @param holders The addresses to claim WPC for
* @param pTokens The list of markets to claim WPC in
* @param borrowers Whether or not to claim WPC earned by borrowing
* @param suppliers Whether or not to claim WPC earned by supplying
*/
function claimWpc(address[] memory holders, PToken[] memory pTokens, bool borrowers, bool suppliers) public {
require(enableWpcClaim, "Claim is not enabled");
for (uint i = 0; i < pTokens.length; i++) {
PToken pToken = pTokens[i];
require(comptroller.isMarketListed(address(pToken)), "market must be listed");
if (borrowers == true) {
Exp memory borrowIndex = Exp({mantissa : pToken.borrowIndex()});
updateWpcBorrowIndex(address(pToken), borrowIndex);
for (uint j = 0; j < holders.length; j++) {
distributeBorrowerWpc(address(pToken), holders[j], borrowIndex, true);
}
}
if (suppliers == true) {
updateWpcSupplyIndex(address(pToken));
for (uint j = 0; j < holders.length; j++) {
distributeSupplierWpc(address(pToken), holders[j], true);
}
}
}
}
/*** WPC Distribution Admin ***/
function _setWpcSpeed(PToken pToken, uint wpcSpeed) public onlyOwner {
setWpcSpeedInternal(pToken, wpcSpeed);
}
function _setEnableWpcClaim(bool state) public onlyOwner {
enableWpcClaim = state;
emit EnableState("enableWpcClaim", state);
}
function _setEnableDistributeMintWpc(bool state) public onlyOwner {
enableDistributeMintWpc = state;
emit EnableState("enableDistributeMintWpc", state);
}
function _setEnableDistributeRedeemWpc(bool state) public onlyOwner {
enableDistributeRedeemWpc = state;
emit EnableState("enableDistributeRedeemWpc", state);
}
function _setEnableDistributeBorrowWpc(bool state) public onlyOwner {
enableDistributeBorrowWpc = state;
emit EnableState("enableDistributeBorrowWpc", state);
}
function _setEnableDistributeRepayBorrowWpc(bool state) public onlyOwner {
enableDistributeRepayBorrowWpc = state;
emit EnableState("enableDistributeRepayBorrowWpc", state);
}
function _setEnableDistributeSeizeWpc(bool state) public onlyOwner {
enableDistributeSeizeWpc = state;
emit EnableState("enableDistributeSeizeWpc", state);
}
function _setEnableDistributeTransferWpc(bool state) public onlyOwner {
enableDistributeTransferWpc = state;
emit EnableState("enableDistributeTransferWpc", state);
}
function _setEnableAll(bool state) public onlyOwner {
_setEnableDistributeMintWpc(state);
_setEnableDistributeRedeemWpc(state);
_setEnableDistributeBorrowWpc(state);
_setEnableDistributeRepayBorrowWpc(state);
_setEnableDistributeSeizeWpc(state);
_setEnableDistributeTransferWpc(state);
_setEnableWpcClaim(state);
}
function _transferWpc(address to, uint amount) public onlyOwner {
_transferToken(address(piggy), to, amount);
}
function _transferToken(address token, address to, uint amount) public onlyOwner {
IERC20 erc20 = IERC20(token);
uint balance = erc20.balanceOf(address(this));
if (balance < amount) {
amount = balance;
}
erc20.transfer(to, amount);
}
function pendingWpcAccrued(address holder, bool borrowers, bool suppliers) public view returns (uint256){
return pendingWpcInternal(holder, borrowers, suppliers);
}
function pendingWpcInternal(address holder, bool borrowers, bool suppliers) internal view returns (uint256){
uint256 pendingWpc = wpcAccrued[holder];
PToken[] memory pTokens = comptroller.getAllMarkets();
for (uint i = 0; i < pTokens.length; i++) {
address pToken = address(pTokens[i]);
uint tmp = 0;
if (borrowers == true) {
tmp = pendingWpcBorrowInternal(holder, pToken);
pendingWpc = add_(pendingWpc, tmp);
}
if (suppliers == true) {
tmp = pendingWpcSupplyInternal(holder, pToken);
pendingWpc = add_(pendingWpc, tmp);
}
}
return pendingWpc;
}
function pendingWpcBorrowInternal(address borrower, address pToken) internal view returns (uint256){
if (enableDistributeBorrowWpc && enableDistributeRepayBorrowWpc) {
Exp memory marketBorrowIndex = Exp({mantissa : PToken(pToken).borrowIndex()});
WpcMarketState memory borrowState = pendingWpcBorrowIndex(pToken, marketBorrowIndex);
Double memory borrowIndex = Double({mantissa : borrowState.index});
Double memory borrowerIndex = Double({mantissa : wpcBorrowerIndex[pToken][borrower]});
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(PToken(pToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
return borrowerDelta;
}
}
return 0;
}
function pendingWpcBorrowIndex(address pToken, Exp memory marketBorrowIndex) internal view returns (WpcMarketState memory){
WpcMarketState memory borrowState = wpcBorrowState[pToken];
uint borrowSpeed = wpcSpeeds[pToken];
uint blockNumber = block.number;
uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));
if (deltaBlocks > 0 && borrowSpeed > 0) {
uint borrowAmount = div_(PToken(pToken).totalBorrows(), marketBorrowIndex);
uint wpcAccrued = mul_(deltaBlocks, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(wpcAccrued, borrowAmount) : Double({mantissa : 0});
Double memory index = add_(Double({mantissa : borrowState.index}), ratio);
borrowState = WpcMarketState({
index : safe224(index.mantissa, "new index exceeds 224 bits"),
block : safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
borrowState = WpcMarketState({
index : borrowState.index,
block : safe32(blockNumber, "block number exceeds 32 bits")
});
}
return borrowState;
}
function pendingWpcSupplyInternal(address supplier, address pToken) internal view returns (uint256){
if (enableDistributeMintWpc && enableDistributeRedeemWpc) {
WpcMarketState memory supplyState = pendingWpcSupplyIndex(pToken);
Double memory supplyIndex = Double({mantissa : supplyState.index});
Double memory supplierIndex = Double({mantissa : wpcSupplierIndex[pToken][supplier]});
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = wpcInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = PToken(pToken).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
return supplierDelta;
}
return 0;
}
function pendingWpcSupplyIndex(address pToken) internal view returns (WpcMarketState memory){
WpcMarketState memory supplyState = wpcSupplyState[pToken];
uint supplySpeed = wpcSpeeds[pToken];
uint blockNumber = block.number;
uint deltaBlocks = sub_(blockNumber, uint(supplyState.block));
if (deltaBlocks > 0 && supplySpeed > 0) {
uint supplyTokens = PToken(pToken).totalSupply();
uint wpcAccrued = mul_(deltaBlocks, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(wpcAccrued, supplyTokens) : Double({mantissa : 0});
Double memory index = add_(Double({mantissa : supplyState.index}), ratio);
supplyState = WpcMarketState({
index : safe224(index.mantissa, "new index exceeds 224 bits"),
block : safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
supplyState = WpcMarketState({
index : supplyState.index,
block : safe32(blockNumber, "block number exceeds 32 bits")
});
}
return supplyState;
}
}
// COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/Comptroller.sol
//Copyright 2020 Compound Labs, Inc.
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//PIGGY-MODIFY: Modified some methods and fields according to WePiggy's business logic
contract Comptroller is ComptrollerStorage, IComptroller, ComptrollerErrorReporter, Exponential, OwnableUpgradeSafe {
// @notice Emitted when an admin supports a market
event MarketListed(PToken pToken);
// @notice Emitted when an account enters a market
event MarketEntered(PToken pToken, address account);
// @notice Emitted when an account exits a market
event MarketExited(PToken pToken, address account);
// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(PToken pToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
// @notice Emitted when maxAssets is changed by admin
event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets);
// @notice Emitted when price oracle is changed
event NewPriceOracle(IPriceOracle oldPriceOracle, IPriceOracle newPriceOracle);
// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
// @notice Emitted when an action is paused on a market
event ActionPaused(PToken pToken, string action, bool pauseState);
/// @notice Emitted when borrow cap for a pToken is changed
event NewBorrowCap(PToken indexed pToken, uint newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
event NewPiggyDistribution(IPiggyDistribution oldPiggyDistribution, IPiggyDistribution newPiggyDistribution);
/// @notice Emitted when mint cap for a pToken is changed
event NewMintCap(PToken indexed pToken, uint newMintCap);
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18;
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18;
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18;
// liquidationIncentiveMantissa must be no less than this value
uint internal constant liquidationIncentiveMinMantissa = 1.0e18;
// liquidationIncentiveMantissa must be no greater than this value
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18;
// for distribute wpc
IPiggyDistribution piggyDistribution;
mapping(address => uint256) public mintCaps;
function initialize() public initializer {
//setting the msg.sender as the initial owner.
super.__Ownable_init();
}
/*** Assets You Are In ***/
function enterMarkets(address[] memory pTokens) public override(IComptroller) returns (uint[] memory) {
uint len = pTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
PToken pToken = PToken(pTokens[i]);
results[i] = uint(addToMarketInternal(pToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param pToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(PToken pToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(pToken)];
// market is not listed, cannot join
if (!marketToJoin.isListed) {
return Error.MARKET_NOT_LISTED;
}
// already joined
if (marketToJoin.accountMembership[borrower] == true) {
return Error.NO_ERROR;
}
// no space, cannot join
if (accountAssets[borrower].length >= maxAssets) {
return Error.TOO_MANY_ASSETS;
}
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(pToken);
emit MarketEntered(pToken, borrower);
return Error.NO_ERROR;
}
function exitMarket(address pTokenAddress) external override(IComptroller) returns (uint) {
PToken pToken = PToken(pTokenAddress);
// Get sender tokensHeld and amountOwed underlying from the pToken
(uint oErr, uint tokensHeld, uint amountOwed,) = pToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed");
// Fail if the sender has a borrow balance
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
// Fail if the sender is not permitted to redeem all of their tokens
uint allowed = redeemAllowedInternal(pTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(pToken)];
// Return true if the sender is not already ‘in’ the market
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
// Set pToken account membership to false
delete marketToExit.accountMembership[msg.sender];
// Delete pToken from the account’s list of assets
// load into memory for faster iteration
PToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == pToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
PToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.pop();
emit MarketExited(pToken, msg.sender);
return uint(Error.NO_ERROR);
}
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (PToken[] memory) {
PToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param pToken The pToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, PToken pToken) external view returns (bool) {
return markets[address(pToken)].accountMembership[account];
}
/*** Policy Hooks ***/
function mintAllowed(address pToken, address minter, uint mintAmount) external override(IComptroller) returns (uint){
// Pausing is a very serious situation - we revert to sound the alarms
require(!pTokenMintGuardianPaused[pToken], "mint is paused");
//Shh - currently unused. It's written here to eliminate compile-time alarms.
minter;
mintAmount;
if (!markets[pToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
uint mintCap = mintCaps[pToken];
if (mintCap != 0) {
uint totalSupply = PToken(pToken).totalSupply();
uint exchangeRate = PToken(pToken).exchangeRateStored();
(MathError mErr, uint balance) = mulScalarTruncate(Exp({mantissa : exchangeRate}), totalSupply);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
(MathError mathErr, uint nextTotalMints) = addUInt(balance, mintAmount);
require(mathErr == MathError.NO_ERROR, "total mint amount overflow");
require(nextTotalMints < mintCap, "market mint cap reached");
}
if (distributeWpcPaused == false) {
piggyDistribution.distributeMintWpc(pToken, minter, false);
}
return uint(Error.NO_ERROR);
}
function mintVerify(address pToken, address minter, uint mintAmount, uint mintTokens) external override(IComptroller) {
//Shh - currently unused. It's written here to eliminate compile-time alarms.
pToken;
minter;
mintAmount;
mintTokens;
}
function redeemAllowed(address pToken, address redeemer, uint redeemTokens) external override(IComptroller) returns (uint){
uint allowed = redeemAllowedInternal(pToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
if (distributeWpcPaused == false) {
piggyDistribution.distributeRedeemWpc(pToken, redeemer, false);
}
return uint(Error.NO_ERROR);
}
/**
* PIGGY-MODIFY:
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param pToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of pTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowedInternal(address pToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[pToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[pToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, PToken(pToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
function redeemVerify(address pToken, address redeemer, uint redeemAmount, uint redeemTokens) external override(IComptroller) {
//Shh - currently unused. It's written here to eliminate compile-time alarms.
pToken;
redeemer;
redeemAmount;
redeemTokens;
}
function borrowAllowed(address pToken, address borrower, uint borrowAmount) external override(IComptroller) returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!pTokenBorrowGuardianPaused[pToken], "borrow is paused");
if (!markets[pToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[pToken].accountMembership[borrower]) {
// only pTokens may call borrowAllowed if borrower not in market
require(msg.sender == pToken, "sender must be pToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(PToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[pToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(PToken(pToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[pToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = PToken(pToken).totalBorrows();
(MathError mathErr, uint nextTotalBorrows) = addUInt(totalBorrows, borrowAmount);
require(mathErr == MathError.NO_ERROR, "total borrows overflow");
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, PToken(pToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
//distribute wpc
if (distributeWpcPaused == false) {
piggyDistribution.distributeBorrowWpc(pToken, borrower, false);
}
return uint(Error.NO_ERROR);
}
function borrowVerify(address pToken, address borrower, uint borrowAmount) external override(IComptroller) {
//Shh - currently unused. It's written here to eliminate compile-time alarms.
pToken;
borrower;
borrowAmount;
}
function repayBorrowAllowed(address pToken, address payer, address borrower, uint repayAmount) external override(IComptroller) returns (uint) {
if (!markets[pToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Shh - currently unused. It's written here to eliminate compile-time alarms.
payer;
borrower;
repayAmount;
//distribute wpc
if (distributeWpcPaused == false) {
piggyDistribution.distributeRepayBorrowWpc(pToken, borrower, false);
}
return uint(Error.NO_ERROR);
}
function repayBorrowVerify(address pToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external override(IComptroller) {
// Shh - currently unused. It's written here to eliminate compile-time alarms.
pToken;
payer;
borrower;
repayAmount;
borrowerIndex;
}
function liquidateBorrowAllowed(
address pTokenBorrowed,
address pTokenCollateral,
address liquidator,
address borrower,
uint repayAmount
) external override(IComptroller) returns (uint){
// Shh - currently unused. It's written here to eliminate compile-time alarms.
liquidator;
if (!markets[pTokenBorrowed].isListed || !markets[pTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = PToken(pTokenBorrowed).borrowBalanceStored(borrower);
(MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa : closeFactorMantissa}), borrowBalance);
if (mathErr != MathError.NO_ERROR) {
return uint(Error.MATH_ERROR);
}
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
function liquidateBorrowVerify(
address pTokenBorrowed,
address pTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens
) external override(IComptroller) {
// Shh - currently unused. It's written here to eliminate compile-time alarms.
pTokenBorrowed;
pTokenCollateral;
liquidator;
borrower;
repayAmount;
seizeTokens;
}
function seizeAllowed(
address pTokenCollateral,
address pTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens
) external override(IComptroller) returns (uint){
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused. It's written here to eliminate compile-time alarms.
seizeTokens;
if (!markets[pTokenCollateral].isListed || !markets[pTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (PToken(pTokenCollateral).comptroller() != PToken(pTokenBorrowed).comptroller()) {
return uint(Error.COMPTROLLER_MISMATCH);
}
//distribute wpc
if (distributeWpcPaused == false) {
piggyDistribution.distributeSeizeWpc(pTokenCollateral, borrower, liquidator, false);
}
return uint(Error.NO_ERROR);
}
function seizeVerify(
address pTokenCollateral,
address pTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens
) external override(IComptroller) {
// Shh - currently unused. It's written here to eliminate compile-time alarms.
pTokenCollateral;
pTokenBorrowed;
liquidator;
borrower;
seizeTokens;
}
function transferAllowed(
address pToken,
address src,
address dst,
uint transferTokens
) external override(IComptroller) returns (uint){
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(pToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
//distribute wpc
if (distributeWpcPaused == false) {
piggyDistribution.distributeTransferWpc(pToken, src, dst, false);
}
return uint(Error.NO_ERROR);
}
function transferVerify(
address pToken,
address src,
address dst,
uint transferTokens
) external override(IComptroller) {
// Shh - currently unused. It's written here to eliminate compile-time alarms.
pToken;
src;
dst;
transferTokens;
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `pTokenBalance` is the number of pTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint pTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, PToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, PToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param pTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address pTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, PToken(pTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param account The account to determine liquidity for
* @param pTokenModify The market to hypothetically redeem/borrow in
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral pToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
PToken pTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars;
uint oErr;
MathError mErr;
// For each asset the account is in
PToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
PToken asset = assets[i];
// Read the balances and exchange rate from the pToken
(oErr, vars.pTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
if (oErr != 0) {// semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa : markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa : vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa : vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> usd (normalized price value)
// pTokenPrice = oraclePrice * exchangeRate
(mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumCollateral += tokensToDenom * pTokenBalance
(mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.pTokenBalance, vars.sumCollateral);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumBorrowPlusEffects += oraclePrice * borrowBalance
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// Calculate effects of interacting with pTokenModify
if (asset == pTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
function liquidateCalculateSeizeTokens(
address pTokenBorrowed,
address pTokenCollateral,
uint actualRepayAmount
) external override(IComptroller) view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(PToken(pTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(PToken(pTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*
* Note: reverts on error
*/
uint exchangeRateMantissa = PToken(pTokenCollateral).exchangeRateStored();
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
MathError mathErr;
(mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, ratio) = divExp(numerator, denominator);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the comptroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(IPriceOracle newOracle) public onlyOwner returns (uint) {
// Track the old oracle for the comptroller
IPriceOracle oldOracle = oracle;
// Set comptroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCloseFactor(uint newCloseFactorMantissa) external onlyOwner returns (uint) {
Exp memory newCloseFactorExp = Exp({mantissa : newCloseFactorMantissa});
Exp memory lowLimit = Exp({mantissa : closeFactorMinMantissa});
if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
Exp memory highLimit = Exp({mantissa : closeFactorMaxMantissa});
if (lessThanExp(highLimit, newCloseFactorExp)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param pToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(PToken pToken, uint newCollateralFactorMantissa) external onlyOwner returns (uint) {
// Verify market is listed
Market storage market = markets[address(pToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa : newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa : collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(pToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(pToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets maxAssets which controls how many markets can be entered
* @dev Admin function to set maxAssets
* @param newMaxAssets New max assets
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setMaxAssets(uint newMaxAssets) external onlyOwner returns (uint) {
uint oldMaxAssets = maxAssets;
maxAssets = newMaxAssets;
emit NewMaxAssets(oldMaxAssets, newMaxAssets);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external onlyOwner returns (uint) {
// Check de-scaled min <= newLiquidationIncentive <= max
Exp memory newLiquidationIncentive = Exp({mantissa : newLiquidationIncentiveMantissa});
Exp memory minLiquidationIncentive = Exp({mantissa : liquidationIncentiveMinMantissa});
if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
Exp memory maxLiquidationIncentive = Exp({mantissa : liquidationIncentiveMaxMantissa});
if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param pToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(PToken pToken) external onlyOwner returns (uint) {
if (markets[address(pToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
markets[address(pToken)] = Market({isListed : true, isMinted : false, collateralFactorMantissa : 0});
_addMarketInternal(address(pToken));
emit MarketListed(pToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address pToken) internal onlyOwner {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != PToken(pToken), "market already added");
}
allMarkets.push(PToken(pToken));
}
/**
* @notice Set the given borrow caps for the given pToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param pTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(PToken[] calldata pTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == owner() || msg.sender == borrowCapGuardian, "only owner or borrow cap guardian can set borrow caps");
uint numMarkets = pTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for (uint i = 0; i < numMarkets; i++) {
borrowCaps[address(pTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(pTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian) external onlyOwner {
// Save current value for inclusion in log
address oldBorrowCapGuardian = borrowCapGuardian;
// Store borrowCapGuardian with value newBorrowCapGuardian
borrowCapGuardian = newBorrowCapGuardian;
// Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public onlyOwner returns (uint) {
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(PToken pToken, bool state) public returns (bool) {
require(markets[address(pToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == owner(), "only pause guardian and owner can pause");
require(msg.sender == owner() || state == true, "only owner can unpause");
pTokenMintGuardianPaused[address(pToken)] = state;
emit ActionPaused(pToken, "Mint", state);
return state;
}
function _setBorrowPaused(PToken pToken, bool state) public returns (bool) {
require(markets[address(pToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == owner(), "only pause guardian and owner can pause");
require(msg.sender == owner() || state == true, "only owner can unpause");
pTokenBorrowGuardianPaused[address(pToken)] = state;
emit ActionPaused(pToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == owner(), "only pause guardian and owner can pause");
require(msg.sender == owner() || state == true, "only owner can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == owner(), "only pause guardian and owner can pause");
require(msg.sender == owner() || state == true, "only owner can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _setDistributeWpcPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == owner(), "only pause guardian and owner can pause");
require(msg.sender == owner() || state == true, "only owner can unpause");
distributeWpcPaused = state;
emit ActionPaused("DistributeWpc", state);
return state;
}
/**
* @notice Sets a new price piggyDistribution for the comptroller
* @dev Admin function to set a new piggy distribution
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPiggyDistribution(IPiggyDistribution newPiggyDistribution) public onlyOwner returns (uint) {
IPiggyDistribution oldPiggyDistribution = piggyDistribution;
piggyDistribution = newPiggyDistribution;
emit NewPiggyDistribution(oldPiggyDistribution, newPiggyDistribution);
return uint(Error.NO_ERROR);
}
function getAllMarkets() public view returns (PToken[] memory){
return allMarkets;
}
function isMarketMinted(address pToken) public view returns (bool){
return markets[pToken].isMinted;
}
function isMarketListed(address pToken) public view returns (bool){
return markets[pToken].isListed;
}
function _setMarketMinted(address pToken, bool status) public {
require(msg.sender == address(piggyDistribution) || msg.sender == owner(), "only PiggyDistribution or owner can update");
markets[pToken].isMinted = status;
}
function _setMarketMintCaps(PToken[] calldata pTokens, uint[] calldata newMintCaps) external onlyOwner {
uint numMarkets = pTokens.length;
uint numMintCaps = newMintCaps.length;
require(numMarkets != 0 && numMarkets == numMintCaps, "invalid input");
for (uint i = 0; i < numMarkets; i++) {
mintCaps[address(pTokens[i])] = newMintCaps[i];
emit NewBorrowCap(pTokens[i], newMintCaps[i]);
}
}
} | Sets maxAssets which controls how many markets can be entered Admin function to set maxAssets newMaxAssets New max assets return uint 0=success, otherwise a failure. (See ErrorReporter for details)/ | function _setMaxAssets(uint newMaxAssets) external onlyOwner returns (uint) {
uint oldMaxAssets = maxAssets;
maxAssets = newMaxAssets;
emit NewMaxAssets(oldMaxAssets, newMaxAssets);
return uint(Error.NO_ERROR);
}
| 36,983 |
./full_match/1/0x4060dBA72344DA74EDaEEAe51a71a57F7E96b6b4/sources/contracts/SkinnyOptimisticOracle.sol | Returns hash of request parameters. These are mapped to the unique request ID to track a request's lifecycle. | function _getRequestHash(Request memory request) private pure returns (bytes32) {
return keccak256(abi.encode(request));
}
| 2,956,463 |
./full_match/1/0x6A0ECf6075dCc9fbCaBf8c2484f82f282A8Ba766/sources/browser/Splitter.sol | distribute any token in contract via addressget balancedistribute | function distributeToken(address tokenAddress) public {
Token _token = Token(tokenAddress);
uint256 balance = _token.balanceOf(address(this));
require(balance > 199, "value too low to distribute");
uint256 percent = balance.div(100);
uint256 half_percent = balance.div(200);
uint256 two_percent = balance.mul(2).div(100);
uint256 three_percent = balance.mul(3).div(100);
uint256 five_percent = balance.mul(5).div(100);
uint256 ten_percent = balance.mul(10).div(100);
uint256 eleven_percent = balance.mul(11).div(100);
uint256 nineteen_percent = balance.mul(19).div(100);
require(_token.transfer(_p1, nineteen_percent.add(half_percent)));
require(_token.transfer(_p2, nineteen_percent.add(half_percent)));
require(_token.transfer(_p3, eleven_percent));
require(_token.transfer(_p4, ten_percent));
require(_token.transfer(_p5, ten_percent));
require(_token.transfer(_p6, five_percent));
require(_token.transfer(_p7, five_percent));
require(_token.transfer(_p8, three_percent));
require(_token.transfer(_p9, three_percent));
require(_token.transfer(_p10, three_percent));
require(_token.transfer(_p11, three_percent));
require(_token.transfer(_p12, three_percent));
require(_token.transfer(_p13, two_percent));
require(_token.transfer(_p14, percent));
require(_token.transfer(_p15, percent));
require(_token.transfer(_p16, percent));
emit DistributedToken(now, msg.sender, balance, _token.symbol());
}
| 9,709,624 |
pragma solidity 0.5.16;
import "./GovernableInit.sol";
// A clone of Governable supporting the Initializable interface and pattern
contract ControllableInit is GovernableInit {
constructor() public {}
function initialize(address _storage) public initializer {
GovernableInit.initialize(_storage);
}
modifier onlyController() {
require(
Storage(_storage()).isController(msg.sender),
"Not a controller"
);
_;
}
modifier onlyControllerOrGovernance() {
require(
(Storage(_storage()).isController(msg.sender) ||
Storage(_storage()).isGovernance(msg.sender)),
"The caller must be controller or governance"
);
_;
}
function controller() public view returns (address) {
return Storage(_storage()).controller();
}
}
pragma solidity 0.5.16;
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "./Storage.sol";
// A clone of Governable supporting the Initializable interface and pattern
contract GovernableInit is Initializable {
bytes32 internal constant _STORAGE_SLOT =
0xa7ec62784904ff31cbcc32d09932a58e7f1e4476e1d041995b37c917990b16dc;
modifier onlyGovernance() {
require(Storage(_storage()).isGovernance(msg.sender), "Not governance");
_;
}
constructor() public {
assert(
_STORAGE_SLOT ==
bytes32(
uint256(keccak256("eip1967.governableInit.storage")) - 1
)
);
}
function initialize(address _store) public initializer {
_setStorage(_store);
}
function _setStorage(address newStorage) private {
bytes32 slot = _STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newStorage)
}
}
function setStorage(address _store) public onlyGovernance {
require(_store != address(0), "new storage shouldn't be empty");
_setStorage(_store);
}
function _storage() internal view returns (address str) {
bytes32 slot = _STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
str := sload(slot)
}
}
function governance() public view returns (address) {
return Storage(_storage()).governance();
}
}
pragma solidity 0.5.16;
contract Storage {
address public governance;
address public controller;
constructor() public {
governance = msg.sender;
}
modifier onlyGovernance() {
require(isGovernance(msg.sender), "Not governance");
_;
}
function setGovernance(address _governance) public onlyGovernance {
require(_governance != address(0), "new governance shouldn't be empty");
governance = _governance;
}
function setController(address _controller) public onlyGovernance {
require(_controller != address(0), "new controller shouldn't be empty");
controller = _controller;
}
function isGovernance(address account) public view returns (bool) {
return account == governance;
}
function isController(address account) public view returns (bool) {
return account == controller;
}
}
pragma solidity 0.5.16;
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/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Detailed.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "./interfaces/IStrategy.sol";
import "./interfaces/IController.sol";
import "./interfaces/IVault.sol";
import "./interfaces/IUpgradeSource.sol";
import "./ControllableInit.sol";
import "./VaultStorage.sol";
contract Vault is
ERC20,
ERC20Detailed,
IVault,
IUpgradeSource,
ControllableInit,
VaultStorage,
ReentrancyGuard
{
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
event Withdraw(address indexed beneficiary, uint256 amount);
event Deposit(address indexed beneficiary, uint256 amount);
event Invest(uint256 amount);
event StrategyAnnounced(address newStrategy, uint256 time);
event StrategyChanged(address newStrategy, address oldStrategy);
modifier whenStrategyDefined() {
require(address(strategy()) != address(0), "Strategy must be defined");
_;
}
// Only smart contracts will be affected by this modifier
modifier defense() {
require(
(msg.sender == tx.origin) || // If it is a normal user and not smart contract,
// then the requirement will pass
IController(controller()).whiteList(msg.sender),
"Access denied for caller"
);
_;
}
// the function is name differently to not cause inheritance clash in truffle and allows tests
function initializeVault(
address _storage,
address _underlying,
uint256 _toInvestNumerator,
uint256 _toInvestDenominator,
uint256 _withdrawFee,
uint256 _maxDepositCap
) public initializer {
require(
_toInvestNumerator <= _toInvestDenominator,
"cannot invest more than 100%"
);
require(_toInvestDenominator != 0, "cannot divide by 0");
ERC20Detailed.initialize(
string(
abi.encodePacked("FORCE_", ERC20Detailed(_underlying).symbol())
),
string(abi.encodePacked("x", ERC20Detailed(_underlying).symbol())),
ERC20Detailed(_underlying).decimals()
);
ControllableInit.initialize(_storage);
ReentrancyGuard.initialize();
uint256 underlyingUnit =
10**uint256(ERC20Detailed(address(_underlying)).decimals());
uint256 implementationDelay = 12 hours;
uint256 strategyChangeDelay = 12 hours;
VaultStorage.initialize(
_underlying,
_toInvestNumerator,
_toInvestDenominator,
underlyingUnit,
_withdrawFee,
_maxDepositCap,
implementationDelay,
strategyChangeDelay
);
}
function strategy() public view returns (address) {
return _strategy();
}
function underlying() public view returns (address) {
return _underlying();
}
function underlyingUnit() public view returns (uint256) {
return _underlyingUnit();
}
function vaultFractionToInvestNumerator() public view returns (uint256) {
return _vaultFractionToInvestNumerator();
}
function vaultFractionToInvestDenominator() public view returns (uint256) {
return _vaultFractionToInvestDenominator();
}
function withdrawFee() public view returns (uint256) {
return _withdrawFee();
}
function totalDeposits() public view returns (uint256) {
return _totalDeposits();
}
function maxDepositCap() public view returns (uint256) {
return _maxDepositCap();
}
function nextImplementation() public view returns (address) {
return _nextImplementation();
}
function nextImplementationTimestamp() public view returns (uint256) {
return _nextImplementationTimestamp();
}
function nextImplementationDelay() public view returns (uint256) {
return _nextImplementationDelay();
}
/**
* Chooses the best strategy and re-invests. If the strategy did not change, it just calls
* forceUnleashed on the current strategy. Call this through controller to claim galactic rewards.
*/
function forceUnleashed()
external
whenStrategyDefined
onlyControllerOrGovernance
{
// ensure that new funds are invested too
invest();
IStrategy(strategy()).forceUnleashed();
}
/*
* Returns the cash balance across all users in this contract.
*/
function underlyingBalanceInVault() public view returns (uint256) {
return IERC20(underlying()).balanceOf(address(this));
}
/* Returns the current underlying (e.g., DAI's) balance together with
* the invested amount (if DAI is invested elsewhere by the strategy).
*/
function underlyingBalanceWithInvestment() public view returns (uint256) {
if (address(strategy()) == address(0)) {
// initial state, when not set
return underlyingBalanceInVault();
}
return
underlyingBalanceInVault().add(
IStrategy(strategy()).investedUnderlyingBalance()
);
}
function getPricePerFullShare() public view returns (uint256) {
return
totalSupply() == 0
? underlyingUnit()
: underlyingUnit().mul(underlyingBalanceWithInvestment()).div(
totalSupply()
);
}
/* get the user's share (in underlying)
*/
function underlyingBalanceWithInvestmentForHolder(address holder)
external
view
returns (uint256)
{
if (totalSupply() == 0) {
return 0;
}
return
underlyingBalanceWithInvestment().mul(balanceOf(holder)).div(
totalSupply()
);
}
function futureStrategy() public view returns (address) {
return _futureStrategy();
}
function strategyUpdateTime() public view returns (uint256) {
return _strategyUpdateTime();
}
function strategyTimeLock() public view returns (uint256) {
return _strategyTimeLock();
}
function canUpdateStrategy(address _strategy) public view returns (bool) {
return
strategy() == address(0) || // no strategy was set yet
(_strategy == futureStrategy() &&
block.timestamp > strategyUpdateTime() &&
strategyUpdateTime() > 0); // or the timelock has passed
}
/**
* Indicates that the strategy update will happen in the future
*/
function announceStrategyUpdate(address _strategy)
public
onlyControllerOrGovernance
{
// records a new timestamp
uint256 when = block.timestamp.add(strategyTimeLock());
_setStrategyUpdateTime(when);
_setFutureStrategy(_strategy);
emit StrategyAnnounced(_strategy, when);
}
/**
* Finalizes (or cancels) the strategy update by resetting the data
*/
function finalizeStrategyUpdate() public onlyControllerOrGovernance {
_setStrategyUpdateTime(0);
_setFutureStrategy(address(0));
}
function setStrategy(address _strategy) public onlyControllerOrGovernance {
require(
canUpdateStrategy(_strategy),
"The strategy exists and switch timelock did not elapse yet"
);
require(_strategy != address(0), "new _strategy cannot be empty");
require(
IStrategy(_strategy).underlying() == address(underlying()),
"Vault underlying must match Strategy underlying"
);
require(
IStrategy(_strategy).vault() == address(this),
"the strategy does not belong to this vault"
);
emit StrategyChanged(_strategy, strategy());
if (address(_strategy) != address(strategy())) {
if (address(strategy()) != address(0)) {
// if the original strategy (no underscore) is defined
IERC20(underlying()).safeApprove(address(strategy()), 0);
IStrategy(strategy()).withdrawAllToVault();
}
_setStrategy(_strategy);
IERC20(underlying()).safeApprove(address(strategy()), 0);
IERC20(underlying()).safeApprove(address(strategy()), uint256(~0));
}
finalizeStrategyUpdate();
}
function setVaultFractionToInvest(uint256 numerator, uint256 denominator)
external
onlyGovernance
{
require(denominator > 0, "denominator must be greater than 0");
require(
numerator <= denominator,
"denominator must be greater than or equal to the numerator"
);
_setVaultFractionToInvestNumerator(numerator);
_setVaultFractionToInvestDenominator(denominator);
}
function setWithdrawFee(uint256 value) external onlyGovernance {
return _setWithdrawFee(value);
}
function setMaxDepositCap(uint256 value) external onlyGovernance {
return _setMaxDepositCap(value);
}
function rebalance() external onlyControllerOrGovernance {
withdrawAll();
invest();
}
function availableToInvestOut() public view returns (uint256) {
uint256 wantInvestInTotal =
underlyingBalanceWithInvestment()
.mul(vaultFractionToInvestNumerator())
.div(vaultFractionToInvestDenominator());
uint256 alreadyInvested =
IStrategy(strategy()).investedUnderlyingBalance();
if (alreadyInvested >= wantInvestInTotal) {
return 0;
} else {
uint256 remainingToInvest = wantInvestInTotal.sub(alreadyInvested);
return
remainingToInvest <= underlyingBalanceInVault() // TODO: we think that the "else" branch of the ternary operation is not // going to get hit
? remainingToInvest
: underlyingBalanceInVault();
}
}
function invest() internal whenStrategyDefined {
uint256 availableAmount = availableToInvestOut();
if (availableAmount > 0) {
IERC20(underlying()).safeTransfer(
address(strategy()),
availableAmount
);
emit Invest(availableAmount);
}
}
/*
* Allows for depositing the underlying asset in exchange for shares.
* Approval is assumed.
*/
function deposit(uint256 amount) external defense {
_deposit(amount, msg.sender, msg.sender);
}
/*
* Allows for depositing the underlying asset in exchange for shares
* assigned to the holder.
* This facilitates depositing for someone else (using DepositHelper)
*/
function depositFor(uint256 amount, address holder) public defense {
_deposit(amount, msg.sender, holder);
}
function withdrawAll()
public
onlyControllerOrGovernance
whenStrategyDefined
{
IStrategy(strategy()).withdrawAllToVault();
}
function withdraw(uint256 numberOfShares) external defense nonReentrant {
require(totalSupply() > 0, "Vault has no shares");
require(numberOfShares > 0, "numberOfShares must be greater than 0");
uint256 totalSupply = totalSupply();
_burn(msg.sender, numberOfShares);
uint256 underlyingAmountToWithdraw =
underlyingBalanceWithInvestment().mul(numberOfShares).div(
totalSupply
);
uint256 originalDepositsToWithdraw =
_totalDeposits().mul(numberOfShares).div(totalSupply);
if (underlyingAmountToWithdraw > underlyingBalanceInVault()) {
// withdraw everything from the strategy to accurately check the share value
if (numberOfShares == totalSupply) {
IStrategy(strategy()).withdrawAllToVault();
} else {
uint256 missing =
underlyingAmountToWithdraw.sub(underlyingBalanceInVault());
IStrategy(strategy()).withdrawToVault(missing);
}
// recalculate to improve accuracy
underlyingAmountToWithdraw = Math.min(
underlyingBalanceWithInvestment().mul(numberOfShares).div(
totalSupply
),
underlyingBalanceInVault()
);
}
uint256 fee = underlyingAmountToWithdraw.mul(withdrawFee()).div(1000);
IERC20(underlying()).safeTransfer(
msg.sender,
underlyingAmountToWithdraw.sub(fee)
);
_setTotalDeposits(_totalDeposits().sub(originalDepositsToWithdraw));
if (fee > 0) {
IERC20(underlying()).safeTransfer(
IController(controller()).treasury(),
fee
);
}
// update the withdrawal amount for the holder
emit Withdraw(msg.sender, underlyingAmountToWithdraw);
}
function _deposit(
uint256 amount,
address sender,
address beneficiary
) internal nonReentrant {
require(amount > 0, "Cannot deposit 0");
require(beneficiary != address(0), "holder must be defined");
require(
maxDepositCap() == 0 ||
totalDeposits().add(amount) <= maxDepositCap(),
"Cannot deposit more than cap"
);
if (address(strategy()) != address(0)) {
require(IStrategy(strategy()).depositArbCheck(), "Too much arb");
}
uint256 toMint =
totalSupply() == 0
? amount
: amount.mul(totalSupply()).div(
underlyingBalanceWithInvestment()
);
_mint(beneficiary, toMint);
IERC20(underlying()).safeTransferFrom(sender, address(this), amount);
_setTotalDeposits(_totalDeposits().add(amount));
// update the contribution amount for the beneficiary
emit Deposit(beneficiary, amount);
}
/**
* Schedules an upgrade for this vault's proxy.
*/
function scheduleUpgrade(address impl) public onlyGovernance {
_setNextImplementation(impl);
_setNextImplementationTimestamp(
block.timestamp.add(nextImplementationDelay())
);
}
function shouldUpgrade() external view returns (bool, address) {
return (
nextImplementationTimestamp() != 0 &&
block.timestamp > nextImplementationTimestamp() &&
nextImplementation() != address(0),
nextImplementation()
);
}
function finalizeUpgrade() external onlyGovernance {
_setNextImplementation(address(0));
_setNextImplementationTimestamp(0);
}
}
pragma solidity 0.5.16;
import "@openzeppelin/upgrades/contracts/Initializable.sol";
contract VaultStorage is Initializable {
bytes32 internal constant _STRATEGY_SLOT =
0xf1a169aa0f736c2813818fdfbdc5755c31e0839c8f49831a16543496b28574ea;
bytes32 internal constant _UNDERLYING_SLOT =
0x1994607607e11d53306ef62e45e3bd85762c58d9bf38b5578bc4a258a26a7371;
bytes32 internal constant _UNDERLYING_UNIT_SLOT =
0xa66bc57d4b4eed7c7687876ca77997588987307cb13ecc23f5e52725192e5fff;
bytes32 internal constant _VAULT_FRACTION_TO_INVEST_NUMERATOR_SLOT =
0x39122c9adfb653455d0c05043bd52fcfbc2be864e832efd3abc72ce5a3d7ed5a;
bytes32 internal constant _VAULT_FRACTION_TO_INVEST_DENOMINATOR_SLOT =
0x469a3bad2fab7b936c45eecd1f5da52af89cead3e2ed7f732b6f3fc92ed32308;
bytes32 internal constant _NEXT_IMPLEMENTATION_SLOT =
0xb1acf527cd7cd1668b30e5a9a1c0d845714604de29ce560150922c9d8c0937df;
bytes32 internal constant _NEXT_IMPLEMENTATION_TIMESTAMP_SLOT =
0x3bc747f4b148b37be485de3223c90b4468252967d2ea7f9fcbd8b6e653f434c9;
bytes32 internal constant _NEXT_IMPLEMENTATION_DELAY_SLOT =
0x82ddc3be3f0c1a6870327f78f4979a0b37b21b16736ef5be6a7a7a35e530bcf0;
bytes32 internal constant _STRATEGY_TIME_LOCK_SLOT =
0x6d02338b2e4c913c0f7d380e2798409838a48a2c4d57d52742a808c82d713d8b;
bytes32 internal constant _FUTURE_STRATEGY_SLOT =
0xb441b53a4e42c2ca9182bc7ede99bedba7a5d9360d9dfbd31fa8ee2dc8590610;
bytes32 internal constant _STRATEGY_UPDATE_TIME_SLOT =
0x56e7c0e75875c6497f0de657009613a32558904b5c10771a825cc330feff7e72;
bytes32 internal constant _WITHDRAW_FEE =
0x3405c96d34f8f0e36eac648034ca7e687437f795bbdbdc2cb7db90a89d519f57;
bytes32 internal constant _TOTAL_DEPOSITS =
0xaf765835ed5af0d235b6c686724ad31fa90e06b3daf1c074d6cc398b8fcef213;
bytes32 internal constant _MAX_DEPOSIT_CAP =
0x0df75d4bdb87be8e3e04e1dc08ec1c98ed6c4147138e5789f0bd448c5c8e1e28;
constructor() public {
assert(
_STRATEGY_SLOT ==
bytes32(uint256(keccak256("eip1967.vaultStorage.strategy")) - 1)
);
assert(
_UNDERLYING_SLOT ==
bytes32(
uint256(keccak256("eip1967.vaultStorage.underlying")) - 1
)
);
assert(
_UNDERLYING_UNIT_SLOT ==
bytes32(
uint256(keccak256("eip1967.vaultStorage.underlyingUnit")) -
1
)
);
assert(
_VAULT_FRACTION_TO_INVEST_NUMERATOR_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.vaultStorage.vaultFractionToInvestNumerator"
)
) - 1
)
);
assert(
_VAULT_FRACTION_TO_INVEST_DENOMINATOR_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.vaultStorage.vaultFractionToInvestDenominator"
)
) - 1
)
);
assert(
_NEXT_IMPLEMENTATION_SLOT ==
bytes32(
uint256(
keccak256("eip1967.vaultStorage.nextImplementation")
) - 1
)
);
assert(
_NEXT_IMPLEMENTATION_TIMESTAMP_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.vaultStorage.nextImplementationTimestamp"
)
) - 1
)
);
assert(
_NEXT_IMPLEMENTATION_DELAY_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.vaultStorage.nextImplementationDelay"
)
) - 1
)
);
assert(
_STRATEGY_TIME_LOCK_SLOT ==
bytes32(
uint256(
keccak256("eip1967.vaultStorage.strategyTimeLock")
) - 1
)
);
assert(
_FUTURE_STRATEGY_SLOT ==
bytes32(
uint256(keccak256("eip1967.vaultStorage.futureStrategy")) -
1
)
);
assert(
_STRATEGY_UPDATE_TIME_SLOT ==
bytes32(
uint256(
keccak256("eip1967.vaultStorage.strategyUpdateTime")
) - 1
)
);
assert(
_WITHDRAW_FEE ==
bytes32(
uint256(keccak256("eip1967.vaultStorage.withdrawFee")) - 1
)
);
assert(
_TOTAL_DEPOSITS ==
bytes32(
uint256(keccak256("eip1967.vaultStorage.totalDeposits")) - 1
)
);
assert(
_MAX_DEPOSIT_CAP ==
bytes32(
uint256(keccak256("eip1967.vaultStorage.maxDepositCap")) - 1
)
);
}
function initialize(
address _underlying,
uint256 _toInvestNumerator,
uint256 _toInvestDenominator,
uint256 _underlyingUnit,
uint256 _withdrawFee_,
uint256 _maxDepositCap_,
uint256 _implementationChangeDelay,
uint256 _strategyChangeDelay
) public initializer {
_setUnderlying(_underlying);
_setVaultFractionToInvestNumerator(_toInvestNumerator);
_setVaultFractionToInvestDenominator(_toInvestDenominator);
_setWithdrawFee(_withdrawFee_);
_setMaxDepositCap(_maxDepositCap_);
_setUnderlyingUnit(_underlyingUnit);
_setNextImplementationDelay(_implementationChangeDelay);
_setStrategyTimeLock(_strategyChangeDelay);
_setStrategyUpdateTime(0);
_setFutureStrategy(address(0));
}
function _setStrategy(address _address) internal {
setAddress(_STRATEGY_SLOT, _address);
}
function _strategy() internal view returns (address) {
return getAddress(_STRATEGY_SLOT);
}
function _setUnderlying(address _address) internal {
setAddress(_UNDERLYING_SLOT, _address);
}
function _underlying() internal view returns (address) {
return getAddress(_UNDERLYING_SLOT);
}
function _setUnderlyingUnit(uint256 _value) internal {
setUint256(_UNDERLYING_UNIT_SLOT, _value);
}
function _underlyingUnit() internal view returns (uint256) {
return getUint256(_UNDERLYING_UNIT_SLOT);
}
function _setVaultFractionToInvestNumerator(uint256 _value) internal {
setUint256(_VAULT_FRACTION_TO_INVEST_NUMERATOR_SLOT, _value);
}
function _vaultFractionToInvestNumerator() internal view returns (uint256) {
return getUint256(_VAULT_FRACTION_TO_INVEST_NUMERATOR_SLOT);
}
function _setVaultFractionToInvestDenominator(uint256 _value) internal {
setUint256(_VAULT_FRACTION_TO_INVEST_DENOMINATOR_SLOT, _value);
}
function _vaultFractionToInvestDenominator()
internal
view
returns (uint256)
{
return getUint256(_VAULT_FRACTION_TO_INVEST_DENOMINATOR_SLOT);
}
function _setWithdrawFee(uint256 _value) internal {
setUint256(_WITHDRAW_FEE, _value);
}
function _withdrawFee() internal view returns (uint256) {
return getUint256(_WITHDRAW_FEE);
}
function _setTotalDeposits(uint256 _value) internal {
setUint256(_TOTAL_DEPOSITS, _value);
}
function _totalDeposits() internal view returns (uint256) {
return getUint256(_TOTAL_DEPOSITS);
}
function _setMaxDepositCap(uint256 _value) internal {
setUint256(_MAX_DEPOSIT_CAP, _value);
}
function _maxDepositCap() internal view returns (uint256) {
return getUint256(_MAX_DEPOSIT_CAP);
}
function _setNextImplementation(address _address) internal {
setAddress(_NEXT_IMPLEMENTATION_SLOT, _address);
}
function _nextImplementation() internal view returns (address) {
return getAddress(_NEXT_IMPLEMENTATION_SLOT);
}
function _setNextImplementationTimestamp(uint256 _value) internal {
setUint256(_NEXT_IMPLEMENTATION_TIMESTAMP_SLOT, _value);
}
function _nextImplementationTimestamp() internal view returns (uint256) {
return getUint256(_NEXT_IMPLEMENTATION_TIMESTAMP_SLOT);
}
function _setNextImplementationDelay(uint256 _value) internal {
setUint256(_NEXT_IMPLEMENTATION_DELAY_SLOT, _value);
}
function _nextImplementationDelay() internal view returns (uint256) {
return getUint256(_NEXT_IMPLEMENTATION_DELAY_SLOT);
}
function _setStrategyTimeLock(uint256 _value) internal {
setUint256(_STRATEGY_TIME_LOCK_SLOT, _value);
}
function _strategyTimeLock() internal view returns (uint256) {
return getUint256(_STRATEGY_TIME_LOCK_SLOT);
}
function _setFutureStrategy(address _value) internal {
setAddress(_FUTURE_STRATEGY_SLOT, _value);
}
function _futureStrategy() internal view returns (address) {
return getAddress(_FUTURE_STRATEGY_SLOT);
}
function _setStrategyUpdateTime(uint256 _value) internal {
setUint256(_STRATEGY_UPDATE_TIME_SLOT, _value);
}
function _strategyUpdateTime() internal view returns (uint256) {
return getUint256(_STRATEGY_UPDATE_TIME_SLOT);
}
function setAddress(bytes32 slot, address _address) private {
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, _address)
}
}
function setUint256(bytes32 slot, uint256 _value) private {
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, _value)
}
}
function getAddress(bytes32 slot) private view returns (address str) {
// solhint-disable-next-line no-inline-assembly
assembly {
str := sload(slot)
}
}
function getUint256(bytes32 slot) private view returns (uint256 str) {
// solhint-disable-next-line no-inline-assembly
assembly {
str := sload(slot)
}
}
uint256[50] private ______gap;
}
pragma solidity 0.5.16;
interface IController {
function whiteList(address _target) external view returns (bool);
function addVaultAndStrategy(address _vault, address _strategy) external;
function forceUnleashed(address _vault) external;
function hasVault(address _vault) external returns (bool);
function salvage(address _token, uint256 amount) external;
function salvageStrategy(
address _strategy,
address _token,
uint256 amount
) external;
function notifyFee(address _underlying, uint256 fee) external;
function profitSharingNumerator() external view returns (uint256);
function profitSharingDenominator() external view returns (uint256);
function treasury() external view returns (address);
}
pragma solidity 0.5.16;
interface IStrategy {
function unsalvagableTokens(address tokens) external view returns (bool);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function vault() external view returns (address);
function withdrawAllToVault() external;
function withdrawToVault(uint256 amount) external;
function investedUnderlyingBalance() external view returns (uint256); // itsNotMuch()
// should only be called by controller
function salvage(
address recipient,
address token,
uint256 amount
) external;
function forceUnleashed() external;
function depositArbCheck() external view returns (bool);
}
pragma solidity 0.5.16;
interface IUpgradeSource {
function shouldUpgrade() external view returns (bool, address);
function finalizeUpgrade() external;
}
pragma solidity 0.5.16;
interface IVault {
function underlyingBalanceInVault() external view returns (uint256);
function underlyingBalanceWithInvestment() external view returns (uint256);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function strategy() external view returns (address);
function setStrategy(address _strategy) external;
function setVaultFractionToInvest(uint256 numerator, uint256 denominator)
external;
function deposit(uint256 amountWei) external;
function depositFor(uint256 amountWei, address holder) external;
function withdrawAll() external;
function withdraw(uint256 numberOfShares) external;
function getPricePerFullShare() external view returns (uint256);
function underlyingBalanceWithInvestmentForHolder(address holder)
external
view
returns (uint256);
// force unleash should be callable only by the controller (by the force unleasher) or by governance
function forceUnleashed() external;
function rebalance() external;
}
pragma solidity ^0.5.0;
import "@openzeppelin/upgrades/contracts/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 Context is Initializable {
// 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;
}
}
pragma solidity ^0.5.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.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;
}
}
pragma solidity ^0.5.0;
import "@openzeppelin/upgrades/contracts/Initializable.sol";
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 {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 Initializable, 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"));
}
uint256[50] private ______gap;
}
pragma solidity ^0.5.0;
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "./IERC20.sol";
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is Initializable, 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.
*/
function initialize(string memory name, string memory symbol, uint8 decimals) public initializer {
_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;
}
uint256[50] private ______gap;
}
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);
}
pragma solidity ^0.5.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.5.5;
/**
* @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 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");
}
}
pragma solidity ^0.5.0;
import "@openzeppelin/upgrades/contracts/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.
*/
contract ReentrancyGuard is Initializable {
// counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
function initialize() public initializer {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @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() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
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;
} | Returns the cash balance across all users in this contract./ | function underlyingBalanceInVault() public view returns (uint256) {
return IERC20(underlying()).balanceOf(address(this));
}
| 37,754 |
// SPDX-License-Identifier: NONE
pragma solidity ^0.8.0;
import "./utils/MerkleProof.sol";
import "./utils/Ownable.sol";
import "./utils/SafeERC20.sol";
import "./interfaces/IERC20.sol";
import "./interfaces/IRewardsAirdropWithLock.sol";
/**
* @title Ruler RewardsAirdropWithLock contract
* @author crypto-pumpkin
* This contract handles multiple rounds of airdrops. It also can (does not have to) enforce a lock up window for claiming. Meaning if the user claimed before the lock up ends, it will charge a penalty.
*/
contract RewardsAirdropWithLock is IRewardsAirdropWithLock, Ownable {
using SafeERC20 for IERC20;
address public override penaltyReceiver;
uint256 public constant override claimWindow = 120 days;
uint256 public constant BASE = 1e18;
AirdropRound[] private airdropRounds;
// roundsIndex => merkleIndex => mask
mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMaps;
modifier onlyNotDisabled(uint256 _roundInd) {
require(!airdropRounds[_roundInd].disabled, "RWL: Round disabled");
_;
}
constructor(address _penaltyReceiver) {
penaltyReceiver = _penaltyReceiver;
}
function updatePaneltyReceiver(address _new) external override onlyOwner {
require(_new != address(0), "RWL: penaltyReceiver is 0");
emit UpdatedPenaltyReceiver(penaltyReceiver, _new);
penaltyReceiver = _new;
}
/**
* @notice add an airdrop round
* @param _token, the token to drop
* @param _merkleRoot, the merkleRoot of the airdrop round
* @param _lockWindow, the amount of time in secs that the rewards are locked, if claim before lock ends, a lockRate panelty is charged. 0 means no lock up period and _lockRate is ignored.
* @param _lockRate, the lockRate to charge if claim before lock ends, 40% lock rate means u only get 60% of the amount if claimed before 1 month (the lock window)
* @param _total, the total amount to be dropped
*/
function addAirdrop(
address _token,
bytes32 _merkleRoot,
uint256 _lockWindow,
uint256 _lockRate,
uint256 _total
) external override onlyOwner returns (uint256) {
require(_token != address(0), "RWL: token is 0");
require(_total > 0, "RWL: total is 0");
require(_merkleRoot.length > 0, "RWL: empty merkle");
IERC20(_token).safeTransferFrom(msg.sender, address(this), _total);
airdropRounds.push(AirdropRound(
_token,
_merkleRoot,
false,
block.timestamp,
_lockWindow,
_lockRate,
_total,
0
));
uint256 index = airdropRounds.length - 1;
emit AddedAirdrop(index, _token, _total);
return index;
}
function updateRoundStatus(uint256 _roundInd, bool _disabled) external override onlyOwner {
emit UpdatedRoundStatus(_roundInd, airdropRounds[_roundInd].disabled, _disabled);
airdropRounds[_roundInd].disabled = _disabled;
}
function claim(
uint256 _roundInd,
uint256 _merkleInd,
address account,
uint256 amount,
bytes32[] calldata merkleProof
) external override onlyNotDisabled(_roundInd) {
require(!isClaimed(_roundInd, _merkleInd), "RWL: Already claimed");
AirdropRound memory airdropRound = airdropRounds[_roundInd];
require(block.timestamp <= airdropRound.startTime + claimWindow, "RWL: Too late");
// Verify the merkle proof.
bytes32 node = keccak256(abi.encodePacked(_merkleInd, account, amount));
require(MerkleProof.verify(merkleProof, airdropRound.merkleRoot, node), "RWL: Invalid proof");
// Mark it claimed and send the token.
airdropRounds[_roundInd].totalClaimed = airdropRound.totalClaimed + amount;
_setClaimed(_roundInd, _merkleInd);
// calculate penalty if any
uint256 claimableAmount = amount;
if (block.timestamp < airdropRound.startTime + airdropRound.lockWindow) {
uint256 penalty = airdropRound.lockRate * amount / BASE;
IERC20(airdropRound.token).safeTransfer(penaltyReceiver, penalty);
claimableAmount -= penalty;
}
IERC20(airdropRound.token).safeTransfer(account, claimableAmount);
emit Claimed(_roundInd, _merkleInd, account, claimableAmount, amount);
}
// collect any token send by mistake, collect target after 120 days
function collectDust(uint256[] calldata _roundInds) external onlyOwner {
for (uint256 i = 0; i < _roundInds.length; i ++) {
AirdropRound memory airdropRound = airdropRounds[_roundInds[i]];
require(block.timestamp > airdropRound.startTime + claimWindow || airdropRound.disabled, "RWL: Not ready");
airdropRounds[_roundInds[i]].disabled = true;
uint256 toCollect = airdropRound.total - airdropRound.totalClaimed;
IERC20(airdropRound.token).safeTransfer(owner(), toCollect);
}
}
function isClaimed(uint256 _roundInd, uint256 _merkleInd) public view override returns (bool) {
uint256 claimedWordIndex = _merkleInd / 256;
uint256 claimedBitIndex = _merkleInd % 256;
uint256 claimedWord = claimedBitMaps[_roundInd][claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
}
function getAllAirdropRounds() external view override returns (AirdropRound[] memory) {
return airdropRounds;
}
function getAirdropRoundsLength() external view override returns (uint256) {
return airdropRounds.length;
}
function getAirdropRounds(uint256 _startInd, uint256 _endInd) external view override returns (AirdropRound[] memory) {
AirdropRound[] memory roundsResults = new AirdropRound[](_endInd - _startInd);
AirdropRound[] memory roundsCopy = airdropRounds;
uint256 resultInd;
for (uint256 i = _startInd; i < _endInd; i++) {
roundsResults[resultInd] = roundsCopy[i];
resultInd++;
}
return roundsResults;
}
function _setClaimed(uint256 _roundInd, uint256 _merkleInd) private {
uint256 claimedWordIndex = _merkleInd / 256;
uint256 claimedBitIndex = _merkleInd % 256;
claimedBitMaps[_roundInd][claimedWordIndex] = claimedBitMaps[_roundInd][claimedWordIndex] | (1 << claimedBitIndex);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^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: None
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.
* @author [email protected]
*
* By initialization, the owner account will be the one that called initializeOwner. 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 {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev COVER: Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @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 == msg.sender, "Ownable: caller is not the owner");
_;
}
/**
* @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.8.0;
import "../interfaces/IERC20.sol";
import "./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 {
uint256 newAllowance = token.allowance(address(this), spender) - 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: No License
pragma solidity ^0.8.0;
/**
* @title Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function balanceOf(address account) external view returns (uint256);
function totalSupply() 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);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
// Allows anyone to claim a token if they exist in a merkle root.
interface IRewardsAirdropWithLock {
event Claimed(uint256 roundInd, uint256 merkleInd, address account, uint256 claimedAmount, uint256 amount);
event UpdatedPenaltyReceiver(address old, address _new);
event UpdatedRoundStatus(uint256 roundInd, bool oldDisabled, bool _newDisabled);
event AddedAirdrop(uint256 roundInd, address token, uint256 total);
struct AirdropRound {
address token;
bytes32 merkleRoot;
bool disabled;
uint256 startTime;
uint256 lockWindow;
uint256 lockRate;
uint256 total;
uint256 totalClaimed;
}
function penaltyReceiver() external view returns (address);
function claimWindow() external view returns (uint256);
// Returns true if the index has been marked claimed.
function isClaimed(uint256 _roundsIndex, uint256 index) external view returns (bool);
// extra view
function getAllAirdropRounds() external returns (AirdropRound[] memory);
function getAirdropRounds(uint256 _startInd, uint256 _endInd) external returns (AirdropRound[] memory);
function getAirdropRoundsLength() external returns (uint256);
// Claim the given amount of the token to the given address. Reverts if the inputs are invalid.
function claim(
uint256 _roundsIndex,
uint256 _merkleIndex,
address account,
uint256 amount,
bytes32[] calldata merkleProof
) external;
// Only owner
function updatePaneltyReceiver(address _new) external;
function addAirdrop(
address _token,
bytes32 _merkleRoot,
uint256 _lockWindow,
uint256 _lockRate,
uint256 _total
) external returns (uint256);
function updateRoundStatus(uint256 _roundInd, bool _disabled) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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);
}
}
}
}
| 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 ====/ 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('')` solhint-disable-next-line no-inline-assembly | function penaltyReceiver() external view returns (address);
function claimWindow() external view returns (uint256);
function isClaimed(uint256 _roundsIndex, uint256 index) external view returns (bool);
function getAllAirdropRounds() external returns (AirdropRound[] memory);
function getAirdropRounds(uint256 _startInd, uint256 _endInd) external returns (AirdropRound[] memory);
function getAirdropRoundsLength() external returns (uint256);
function claim(
uint256 _roundsIndex,
uint256 _merkleIndex,
address account,
uint256 amount,
bytes32[] calldata merkleProof
) external;
function updatePaneltyReceiver(address _new) external;
function addAirdrop(
address _token,
bytes32 _merkleRoot,
uint256 _lockWindow,
uint256 _lockRate,
uint256 _total
) external returns (uint256);
function updateRoundStatus(uint256 _roundInd, bool _disabled) external;
}
pragma solidity ^0.8.0;
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
return (codehash != accountHash && codehash != 0x0);
}
| 1,531,914 |
./full_match/5/0x95422c7d13F0A80B6CCb47F8346E21396823bfE6/sources/src/contracts/PublicLock/PublicLockV11.sol | Change the maximum number of keys the lock can edit _maxNumberOfKeys uint the maximum number of keys Can't be smaller than the existing supply/ | function setMaxNumberOfKeys (uint _maxNumberOfKeys) external {
_onlyLockManager();
if (_maxNumberOfKeys < _totalSupply) {
revert CANT_BE_SMALLER_THAN_SUPPLY();
}
maxNumberOfKeys = _maxNumberOfKeys;
}
| 11,630,620 |
./partial_match/4/0x6480e156865Bbb84Ba94d53dC09f667bdC2B371a/sources/Contract.sol | Получение имен кандидатов./ | function getProposalsName() public view isBallotExist returns(bytes32[] memory) {
return ballots[ballots.length - 1].proposalsName;
}
| 8,508,798 |
pragma solidity ^0.5.0;
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, 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 unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 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 unsigned integers, 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 unsigned integers, 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 unsigned integers 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;
}
}
// File: openzeppelin-solidity/contracts/ownership/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 private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @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 OwnershipTransferred(_owner, address(0));
_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;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query 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 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 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) {
_transfer(msg.sender, 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) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @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) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
/**
* @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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
// File: contracts/assettoken/library/AssetTokenL.sol
/*
Copyright 2018, CONDA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** @title AssetTokenL library. */
library AssetTokenL {
using SafeMath for uint256;
///////////////////
// Struct Parameters (passed as parameter to library)
///////////////////
struct Supply {
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes. TransfersAndMints-index when the change
// occurred is also included
mapping (address => Checkpoint[]) balances;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Minting cap max amount of tokens
uint256 cap;
// When successfully funded
uint256 goal;
//crowdsale start
uint256 startTime;
//crowdsale end
uint256 endTime;
//crowdsale dividends
Dividend[] dividends;
//counter per address how much was claimed in continuous way
//note: counter also increases when recycled and tried to claim in continous way
mapping (address => uint256) dividendsClaimed;
uint256 tokenActionIndex; //only modify within library
}
struct Availability {
// Flag that determines if the token is yet alive.
// Meta data cannot be changed anymore (except capitalControl)
bool tokenAlive;
// Flag that determines if the token is transferable or not.
bool transfersEnabled;
// Flag that minting is finished
bool mintingPhaseFinished;
// Flag that minting is paused
bool mintingPaused;
}
struct Roles {
// role that can pause/resume
address pauseControl;
// role that can rescue accidentally sent tokens
address tokenRescueControl;
// role that can mint during crowdsale (usually controller)
address mintControl;
}
///////////////////
// Structs (saved to blockchain)
///////////////////
/// @dev `Dividend` is the structure that saves the status of a dividend distribution
struct Dividend {
uint256 currentTokenActionIndex;
uint256 timestamp;
DividendType dividendType;
address dividendToken;
uint256 amount;
uint256 claimedAmount;
uint256 totalSupply;
bool recycled;
mapping (address => bool) claimed;
}
/// @dev Dividends can be of those types.
enum DividendType { Ether, ERC20 }
/** @dev Checkpoint` is the structure that attaches a history index to a given value
* @notice That uint128 is used instead of uint/uint256. That's to save space. Should be big enough (feedback from audit)
*/
struct Checkpoint {
// `currentTokenActionIndex` is the index when the value was generated. It's uint128 to save storage space
uint128 currentTokenActionIndex;
// `value` is the amount of tokens at a specific index. It's uint128 to save storage space
uint128 value;
}
///////////////////
// Functions
///////////////////
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract. Check for availability must be done before.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(Supply storage _self, Availability storage /*_availability*/, address _from, address _to, uint256 _amount) public {
// Do not allow transfer to 0x0 or the token contract itself
require(_to != address(0), "addr0");
require(_to != address(this), "target self");
// If the amount being transfered is more than the balance of the
// account the transfer throws
uint256 previousBalanceFrom = balanceOfNow(_self, _from);
require(previousBalanceFrom >= _amount, "not enough");
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(_self, _self.balances[_from], previousBalanceFrom.sub(_amount));
// Then update the balance array with the new value for the address
// receiving the tokens
uint256 previousBalanceTo = balanceOfNow(_self, _to);
updateValueAtNow(_self, _self.balances[_to], previousBalanceTo.add(_amount));
//info: don't move this line inside updateValueAtNow (because transfer is 2 actions)
increaseTokenActionIndex(_self);
// An event to make the transfer easy to find on the blockchain
emit Transfer(_from, _to, _amount);
}
function increaseTokenActionIndex(Supply storage _self) private {
_self.tokenActionIndex = _self.tokenActionIndex.add(1);
emit TokenActionIndexIncreased(_self.tokenActionIndex, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` of his tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(Supply storage _self, address _spender, uint256 _amount) public returns (bool success) {
// 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((_amount == 0) || (_self.allowed[msg.sender][_spender] == 0), "amount");
_self.allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/// @notice Increase the amount of tokens that an owner allowed to a spender.
/// @dev 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.
/// @return True if the approval was successful
function increaseApproval(Supply storage _self, address _spender, uint256 _addedValue) public returns (bool) {
_self.allowed[msg.sender][_spender] = _self.allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, _self.allowed[msg.sender][_spender]);
return true;
}
/// @notice Decrease the amount of tokens that an owner allowed to a spender.
/// @dev 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.
/// @return True if the approval was successful
function decreaseApproval(Supply storage _self, address _spender, uint256 _subtractedValue) public returns (bool) {
uint256 oldValue = _self.allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
_self.allowed[msg.sender][_spender] = 0;
} else {
_self.allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, _self.allowed[msg.sender][_spender]);
return true;
}
/// @notice Send `_amount` tokens to `_to` from `_from` if it is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(Supply storage _supply, Availability storage _availability, address _from, address _to, uint256 _amount)
public
returns (bool success)
{
// The standard ERC 20 transferFrom functionality
require(_supply.allowed[_from][msg.sender] >= _amount, "allowance");
_supply.allowed[_from][msg.sender] = _supply.allowed[_from][msg.sender].sub(_amount);
doTransfer(_supply, _availability, _from, _to, _amount);
return true;
}
/// @notice Send `_amount` tokens to `_to` from `_from` WITHOUT approval. UseCase: notar transfers from lost wallet
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @param _fullAmountRequired Full amount required (causes revert if not).
/// @return True if the transfer was successful
function enforcedTransferFrom(
Supply storage _self,
Availability storage _availability,
address _from,
address _to,
uint256 _amount,
bool _fullAmountRequired)
public
returns (bool success)
{
if(_fullAmountRequired && _amount != balanceOfNow(_self, _from))
{
revert("Only full amount in case of lost wallet is allowed");
}
doTransfer(_self, _availability, _from, _to, _amount);
emit SelfApprovedTransfer(msg.sender, _from, _to, _amount);
return true;
}
////////////////
// Miniting
////////////////
/// @notice 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(Supply storage _self, address _to, uint256 _amount) public returns (bool) {
uint256 curTotalSupply = totalSupplyNow(_self);
uint256 previousBalanceTo = balanceOfNow(_self, _to);
// Check cap
require(curTotalSupply.add(_amount) <= _self.cap, "cap"); //leave inside library to never go over cap
// Check timeframe
require(_self.startTime <= now, "too soon");
require(_self.endTime >= now, "too late");
updateValueAtNow(_self, _self.totalSupplyHistory, curTotalSupply.add(_amount));
updateValueAtNow(_self, _self.balances[_to], previousBalanceTo.add(_amount));
//info: don't move this line inside updateValueAtNow (because transfer is 2 actions)
increaseTokenActionIndex(_self);
emit MintDetailed(msg.sender, _to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at `_specificTransfersAndMintsIndex`
/// @param _owner The address from which the balance will be retrieved
/// @param _specificTransfersAndMintsIndex The balance at index
/// @return The balance at `_specificTransfersAndMintsIndex`
function balanceOfAt(Supply storage _self, address _owner, uint256 _specificTransfersAndMintsIndex) public view returns (uint256) {
return getValueAt(_self.balances[_owner], _specificTransfersAndMintsIndex);
}
function balanceOfNow(Supply storage _self, address _owner) public view returns (uint256) {
return getValueAt(_self.balances[_owner], _self.tokenActionIndex);
}
/// @dev Total amount of tokens at `_specificTransfersAndMintsIndex`.
/// @param _specificTransfersAndMintsIndex The totalSupply at index
/// @return The total amount of tokens at `_specificTransfersAndMintsIndex`
function totalSupplyAt(Supply storage _self, uint256 _specificTransfersAndMintsIndex) public view returns(uint256) {
return getValueAt(_self.totalSupplyHistory, _specificTransfersAndMintsIndex);
}
function totalSupplyNow(Supply storage _self) public view returns(uint256) {
return getValueAt(_self.totalSupplyHistory, _self.tokenActionIndex);
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given index
/// @param checkpoints The history of values being queried
/// @param _specificTransfersAndMintsIndex The index to retrieve the history checkpoint value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint256 _specificTransfersAndMintsIndex) private view returns (uint256) {
// requested before a check point was ever created for this token
if (checkpoints.length == 0 || checkpoints[0].currentTokenActionIndex > _specificTransfersAndMintsIndex) {
return 0;
}
// Shortcut for the actual value
if (_specificTransfersAndMintsIndex >= checkpoints[checkpoints.length-1].currentTokenActionIndex) {
return checkpoints[checkpoints.length-1].value;
}
// Binary search of the value in the array
uint256 min = 0;
uint256 max = checkpoints.length-1;
while (max > min) {
uint256 mid = (max + min + 1)/2;
if (checkpoints[mid].currentTokenActionIndex<=_specificTransfersAndMintsIndex) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Supply storage _self, Checkpoint[] storage checkpoints, uint256 _value) private {
require(_value == uint128(_value), "invalid cast1");
require(_self.tokenActionIndex == uint128(_self.tokenActionIndex), "invalid cast2");
checkpoints.push(Checkpoint(
uint128(_self.tokenActionIndex),
uint128(_value)
));
}
/// @dev Function to stop minting new tokens.
/// @return True if the operation was successful.
function finishMinting(Availability storage _self) public returns (bool) {
if(_self.mintingPhaseFinished) {
return false;
}
_self.mintingPhaseFinished = true;
emit MintFinished(msg.sender);
return true;
}
/// @notice Reopening crowdsale means minting is again possible. UseCase: notary approves and does that.
/// @return True if the operation was successful.
function reopenCrowdsale(Availability storage _self) public returns (bool) {
if(_self.mintingPhaseFinished == false) {
return false;
}
_self.mintingPhaseFinished = false;
emit Reopened(msg.sender);
return true;
}
/// @notice Set roles/operators.
/// @param _pauseControl pause control.
/// @param _tokenRescueControl token rescue control (accidentally assigned tokens).
function setRoles(Roles storage _self, address _pauseControl, address _tokenRescueControl) public {
require(_pauseControl != address(0), "addr0");
require(_tokenRescueControl != address(0), "addr0");
_self.pauseControl = _pauseControl;
_self.tokenRescueControl = _tokenRescueControl;
emit RolesChanged(msg.sender, _pauseControl, _tokenRescueControl);
}
/// @notice Set mint control.
function setMintControl(Roles storage _self, address _mintControl) public {
require(_mintControl != address(0), "addr0");
_self.mintControl = _mintControl;
emit MintControlChanged(msg.sender, _mintControl);
}
/// @notice Set token alive which can be seen as not in draft state anymore.
function setTokenAlive(Availability storage _self) public {
_self.tokenAlive = true;
}
////////////////
// Pausing token for unforeseen reasons
////////////////
/// @notice pause transfer.
/// @param _transfersEnabled True if transfers are allowed.
function pauseTransfer(Availability storage _self, bool _transfersEnabled) public
{
_self.transfersEnabled = _transfersEnabled;
if(_transfersEnabled) {
emit TransferResumed(msg.sender);
} else {
emit TransferPaused(msg.sender);
}
}
/// @notice calling this can enable/disable capital increase/decrease flag
/// @param _mintingEnabled True if minting is allowed
function pauseCapitalIncreaseOrDecrease(Availability storage _self, bool _mintingEnabled) public
{
_self.mintingPaused = (_mintingEnabled == false);
if(_mintingEnabled) {
emit MintingResumed(msg.sender);
} else {
emit MintingPaused(msg.sender);
}
}
/// @notice Receives ether to be distriubted to all token owners
function depositDividend(Supply storage _self, uint256 msgValue)
public
{
require(msgValue > 0, "amount0");
// gets the current number of total token distributed
uint256 currentSupply = totalSupplyNow(_self);
// a deposit without investment would end up in unclaimable deposit for token holders
require(currentSupply > 0, "0investors");
// creates a new index for the dividends
uint256 dividendIndex = _self.dividends.length;
// Stores the current meta data for the dividend payout
_self.dividends.push(
Dividend(
_self.tokenActionIndex, // current index used for claiming
block.timestamp, // Timestamp of the distribution
DividendType.Ether, // Type of dividends
address(0),
msgValue, // Total amount that has been distributed
0, // amount that has been claimed
currentSupply, // Total supply now
false // Already recylced
)
);
emit DividendDeposited(msg.sender, _self.tokenActionIndex, msgValue, currentSupply, dividendIndex);
}
/// @notice Receives ERC20 to be distriubted to all token owners
function depositERC20Dividend(Supply storage _self, address _dividendToken, uint256 _amount, address baseCurrency)
public
{
require(_amount > 0, "amount0");
require(_dividendToken == baseCurrency, "not baseCurrency");
// gets the current number of total token distributed
uint256 currentSupply = totalSupplyNow(_self);
// a deposit without investment would end up in unclaimable deposit for token holders
require(currentSupply > 0, "0investors");
// creates a new index for the dividends
uint256 dividendIndex = _self.dividends.length;
// Stores the current meta data for the dividend payout
_self.dividends.push(
Dividend(
_self.tokenActionIndex, // index that counts up on transfers and mints
block.timestamp, // Timestamp of the distribution
DividendType.ERC20,
_dividendToken,
_amount, // Total amount that has been distributed
0, // amount that has been claimed
currentSupply, // Total supply now
false // Already recylced
)
);
// it shouldn't return anything but according to ERC20 standard it could if badly implemented
// IMPORTANT: potentially a call with reentrance -> do at the end
require(ERC20(_dividendToken).transferFrom(msg.sender, address(this), _amount), "transferFrom");
emit DividendDeposited(msg.sender, _self.tokenActionIndex, _amount, currentSupply, dividendIndex);
}
/// @notice Function to claim dividends for msg.sender
/// @dev dividendsClaimed should not be handled here.
function claimDividend(Supply storage _self, uint256 _dividendIndex) public {
// Loads the details for the specific Dividend payment
Dividend storage dividend = _self.dividends[_dividendIndex];
// Devidends should not have been claimed already
require(dividend.claimed[msg.sender] == false, "claimed");
// Devidends should not have been recycled already
require(dividend.recycled == false, "recycled");
// get the token balance at the time of the dividend distribution
uint256 balance = balanceOfAt(_self, msg.sender, dividend.currentTokenActionIndex.sub(1));
// calculates the amount of dividends that can be claimed
uint256 claim = balance.mul(dividend.amount).div(dividend.totalSupply);
// flag that dividends have been claimed
dividend.claimed[msg.sender] = true;
dividend.claimedAmount = SafeMath.add(dividend.claimedAmount, claim);
claimThis(dividend.dividendType, _dividendIndex, msg.sender, claim, dividend.dividendToken);
}
/// @notice Claim all dividends.
/// @dev dividendsClaimed counter should only increase when claimed in hole-free way.
function claimDividendAll(Supply storage _self) public {
claimLoopInternal(_self, _self.dividendsClaimed[msg.sender], (_self.dividends.length-1));
}
/// @notice Claim dividends in batches. In case claimDividendAll runs out of gas.
/// @dev dividendsClaimed counter should only increase when claimed in hole-free way.
/// @param _startIndex start index (inclusive number).
/// @param _endIndex end index (inclusive number).
function claimInBatches(Supply storage _self, uint256 _startIndex, uint256 _endIndex) public {
claimLoopInternal(_self, _startIndex, _endIndex);
}
/// @notice Claim loop of batch claim and claim all.
/// @dev dividendsClaimed counter should only increase when claimed in hole-free way.
/// @param _startIndex start index (inclusive number).
/// @param _endIndex end index (inclusive number).
function claimLoopInternal(Supply storage _self, uint256 _startIndex, uint256 _endIndex) private {
require(_startIndex <= _endIndex, "start after end");
//early exit if already claimed
require(_self.dividendsClaimed[msg.sender] < _self.dividends.length, "all claimed");
uint256 dividendsClaimedTemp = _self.dividendsClaimed[msg.sender];
// Cycle through all dividend distributions and make the payout
for (uint256 i = _startIndex; i <= _endIndex; i++) {
if (_self.dividends[i].recycled == true) {
//recycled and tried to claim in continuous way internally counts as claimed
dividendsClaimedTemp = SafeMath.add(i, 1);
}
else if (_self.dividends[i].claimed[msg.sender] == false) {
dividendsClaimedTemp = SafeMath.add(i, 1);
claimDividend(_self, i);
}
}
// This is done after the loop to reduce writes.
// Remembers what has been claimed after hole-free claiming procedure.
// IMPORTANT: do only if batch claim docks on previous claim to avoid unexpected claim all behaviour.
if(_startIndex <= _self.dividendsClaimed[msg.sender]) {
_self.dividendsClaimed[msg.sender] = dividendsClaimedTemp;
}
}
/// @notice Dividends which have not been claimed can be claimed by owner after timelock (to avoid loss)
/// @param _dividendIndex index of dividend to recycle.
/// @param _recycleLockedTimespan timespan required until possible.
/// @param _currentSupply current supply.
function recycleDividend(Supply storage _self, uint256 _dividendIndex, uint256 _recycleLockedTimespan, uint256 _currentSupply) public {
// Get the dividend distribution
Dividend storage dividend = _self.dividends[_dividendIndex];
// should not have been recycled already
require(dividend.recycled == false, "recycled");
// The recycle time has to be over
require(dividend.timestamp < SafeMath.sub(block.timestamp, _recycleLockedTimespan), "timeUp");
// Devidends should not have been claimed already
require(dividend.claimed[msg.sender] == false, "claimed");
//
//refund
//
// The amount, which has not been claimed is distributed to token owner
_self.dividends[_dividendIndex].recycled = true;
// calculates the amount of dividends that can be claimed
uint256 claim = SafeMath.sub(dividend.amount, dividend.claimedAmount);
// flag that dividends have been claimed
dividend.claimed[msg.sender] = true;
dividend.claimedAmount = SafeMath.add(dividend.claimedAmount, claim);
claimThis(dividend.dividendType, _dividendIndex, msg.sender, claim, dividend.dividendToken);
emit DividendRecycled(msg.sender, _self.tokenActionIndex, claim, _currentSupply, _dividendIndex);
}
/// @dev the core claim function of single dividend.
function claimThis(DividendType _dividendType, uint256 _dividendIndex, address payable _beneficiary, uint256 _claim, address _dividendToken)
private
{
// transfer the dividends to the token holder
if (_claim > 0) {
if (_dividendType == DividendType.Ether) {
_beneficiary.transfer(_claim);
}
else if (_dividendType == DividendType.ERC20) {
require(ERC20(_dividendToken).transfer(_beneficiary, _claim), "transfer");
}
else {
revert("unknown type");
}
emit DividendClaimed(_beneficiary, _dividendIndex, _claim);
}
}
/// @notice If this contract gets a balance in some other ERC20 contract - or even iself - then we can rescue it.
/// @param _foreignTokenAddress token where contract has balance.
/// @param _to the beneficiary.
function rescueToken(Availability storage _self, address _foreignTokenAddress, address _to) public
{
require(_self.mintingPhaseFinished, "unfinished");
ERC20(_foreignTokenAddress).transfer(_to, ERC20(_foreignTokenAddress).balanceOf(address(this)));
}
///////////////////
// Events (must be redundant in calling contract to work!)
///////////////////
event Transfer(address indexed from, address indexed to, uint256 value);
event SelfApprovedTransfer(address indexed initiator, address indexed from, address indexed to, uint256 value);
event MintDetailed(address indexed initiator, address indexed to, uint256 amount);
event MintFinished(address indexed initiator);
event Approval(address indexed owner, address indexed spender, uint256 value);
event TransferPaused(address indexed initiator);
event TransferResumed(address indexed initiator);
event MintingPaused(address indexed initiator);
event MintingResumed(address indexed initiator);
event Reopened(address indexed initiator);
event DividendDeposited(address indexed depositor, uint256 transferAndMintIndex, uint256 amount, uint256 totalSupply, uint256 dividendIndex);
event DividendClaimed(address indexed claimer, uint256 dividendIndex, uint256 claim);
event DividendRecycled(address indexed recycler, uint256 transferAndMintIndex, uint256 amount, uint256 totalSupply, uint256 dividendIndex);
event RolesChanged(address indexed initiator, address pauseControl, address tokenRescueControl);
event MintControlChanged(address indexed initiator, address mintControl);
event TokenActionIndexIncreased(uint256 tokenActionIndex, uint256 blocknumber);
}
// File: contracts/assettoken/interface/IBasicAssetToken.sol
interface IBasicAssetToken {
//AssetToken specific
function getLimits() external view returns (uint256, uint256, uint256, uint256);
function isTokenAlive() external view returns (bool);
function setMetaData(
string calldata _name,
string calldata _symbol,
address _tokenBaseCurrency,
uint256 _cap,
uint256 _goal,
uint256 _startTime,
uint256 _endTime)
external;
//Mintable
function mint(address _to, uint256 _amount) external returns (bool);
function finishMinting() external returns (bool);
//ERC20
function balanceOf(address _owner) external view returns (uint256 balance);
function approve(address _spender, uint256 _amount) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function totalSupply() external view returns (uint256);
function increaseApproval(address _spender, uint256 _addedValue) external returns (bool);
function decreaseApproval(address _spender, uint256 _subtractedValue) external returns (bool);
function transfer(address _to, uint256 _amount) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _amount) external returns (bool success);
}
// File: contracts/assettoken/abstract/IBasicAssetTokenFull.sol
contract IBasicAssetTokenFull is IBasicAssetToken {
function checkCanSetMetadata() internal returns (bool);
function getCap() public view returns (uint256);
function getGoal() public view returns (uint256);
function getStart() public view returns (uint256);
function getEnd() public view returns (uint256);
function getLimits() public view returns (uint256, uint256, uint256, uint256);
function setMetaData(
string calldata _name,
string calldata _symbol,
address _tokenBaseCurrency,
uint256 _cap,
uint256 _goal,
uint256 _startTime,
uint256 _endTime)
external;
function getTokenRescueControl() public view returns (address);
function getPauseControl() public view returns (address);
function isTransfersPaused() public view returns (bool);
function setMintControl(address _mintControl) public;
function setRoles(address _pauseControl, address _tokenRescueControl) public;
function setTokenAlive() public;
function isTokenAlive() public view returns (bool);
function balanceOf(address _owner) public view returns (uint256 balance);
function approve(address _spender, uint256 _amount) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
function totalSupply() public view returns (uint256);
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool);
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool);
function finishMinting() public returns (bool);
function rescueToken(address _foreignTokenAddress, address _to) public;
function balanceOfAt(address _owner, uint256 _specificTransfersAndMintsIndex) public view returns (uint256);
function totalSupplyAt(uint256 _specificTransfersAndMintsIndex) public view returns(uint256);
function enableTransfers(bool _transfersEnabled) public;
function pauseTransfer(bool _transfersEnabled) public;
function pauseCapitalIncreaseOrDecrease(bool _mintingEnabled) public;
function isMintingPaused() public view returns (bool);
function mint(address _to, uint256 _amount) public returns (bool);
function transfer(address _to, uint256 _amount) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success);
function enableTransferInternal(bool _transfersEnabled) internal;
function reopenCrowdsaleInternal() internal returns (bool);
function transferFromInternal(address _from, address _to, uint256 _amount) internal returns (bool success);
function enforcedTransferFromInternal(address _from, address _to, uint256 _value, bool _fullAmountRequired) internal returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
event MintDetailed(address indexed initiator, address indexed to, uint256 amount);
event MintFinished(address indexed initiator);
event TransferPaused(address indexed initiator);
event TransferResumed(address indexed initiator);
event Reopened(address indexed initiator);
event MetaDataChanged(address indexed initiator, string name, string symbol, address baseCurrency, uint256 cap, uint256 goal);
event RolesChanged(address indexed initiator, address _pauseControl, address _tokenRescueControl);
event MintControlChanged(address indexed initiator, address mintControl);
}
// File: contracts/assettoken/BasicAssetToken.sol
/*
Copyright 2018, CONDA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** @title Basic AssetToken. This contract includes the basic AssetToken features */
contract BasicAssetToken is IBasicAssetTokenFull, Ownable {
using SafeMath for uint256;
using AssetTokenL for AssetTokenL.Supply;
using AssetTokenL for AssetTokenL.Availability;
using AssetTokenL for AssetTokenL.Roles;
///////////////////
// Variables
///////////////////
string private _name;
string private _symbol;
// The token's name
function name() public view returns (string memory) {
return _name;
}
// Fixed number of 0 decimals like real world equity
function decimals() public pure returns (uint8) {
return 0;
}
// An identifier
function symbol() public view returns (string memory) {
return _symbol;
}
// 1000 is version 1
uint16 public constant version = 2000;
// Defines the baseCurrency of the token
address public baseCurrency;
// Supply: balance, checkpoints etc.
AssetTokenL.Supply supply;
// Availability: what's paused
AssetTokenL.Availability availability;
// Roles: who is entitled
AssetTokenL.Roles roles;
///////////////////
// Simple state getters
///////////////////
function isMintingPaused() public view returns (bool) {
return availability.mintingPaused;
}
function isMintingPhaseFinished() public view returns (bool) {
return availability.mintingPhaseFinished;
}
function getPauseControl() public view returns (address) {
return roles.pauseControl;
}
function getTokenRescueControl() public view returns (address) {
return roles.tokenRescueControl;
}
function getMintControl() public view returns (address) {
return roles.mintControl;
}
function isTransfersPaused() public view returns (bool) {
return !availability.transfersEnabled;
}
function isTokenAlive() public view returns (bool) {
return availability.tokenAlive;
}
function getCap() public view returns (uint256) {
return supply.cap;
}
function getGoal() public view returns (uint256) {
return supply.goal;
}
function getStart() public view returns (uint256) {
return supply.startTime;
}
function getEnd() public view returns (uint256) {
return supply.endTime;
}
function getLimits() public view returns (uint256, uint256, uint256, uint256) {
return (supply.cap, supply.goal, supply.startTime, supply.endTime);
}
function getCurrentHistoryIndex() public view returns (uint256) {
return supply.tokenActionIndex;
}
///////////////////
// Events
///////////////////
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
event MintDetailed(address indexed initiator, address indexed to, uint256 amount);
event MintFinished(address indexed initiator);
event TransferPaused(address indexed initiator);
event TransferResumed(address indexed initiator);
event MintingPaused(address indexed initiator);
event MintingResumed(address indexed initiator);
event Reopened(address indexed initiator);
event MetaDataChanged(address indexed initiator, string name, string symbol, address baseCurrency, uint256 cap, uint256 goal);
event RolesChanged(address indexed initiator, address pauseControl, address tokenRescueControl);
event MintControlChanged(address indexed initiator, address mintControl);
event TokenActionIndexIncreased(uint256 tokenActionIndex, uint256 blocknumber);
///////////////////
// Modifiers
///////////////////
modifier onlyPauseControl() {
require(msg.sender == roles.pauseControl, "pauseCtrl");
_;
}
//can be overwritten in inherited contracts...
function _canDoAnytime() internal view returns (bool) {
return false;
}
modifier onlyOwnerOrOverruled() {
if(_canDoAnytime() == false) {
require(isOwner(), "only owner");
}
_;
}
modifier canMint() {
if(_canDoAnytime() == false) {
require(canMintLogic(), "canMint");
}
_;
}
function canMintLogic() private view returns (bool) {
return msg.sender == roles.mintControl && availability.tokenAlive && !availability.mintingPhaseFinished && !availability.mintingPaused;
}
//can be overwritten in inherited contracts...
function checkCanSetMetadata() internal returns (bool) {
if(_canDoAnytime() == false) {
require(isOwner(), "owner only");
require(!availability.tokenAlive, "alive");
require(!availability.mintingPhaseFinished, "finished");
}
return true;
}
modifier canSetMetadata() {
checkCanSetMetadata();
_;
}
modifier onlyTokenAlive() {
require(availability.tokenAlive, "not alive");
_;
}
modifier onlyTokenRescueControl() {
require(msg.sender == roles.tokenRescueControl, "rescueCtrl");
_;
}
modifier canTransfer() {
require(availability.transfersEnabled, "paused");
_;
}
///////////////////
// Set / Get Metadata
///////////////////
/// @notice Change the token's metadata.
/// @dev Time is via block.timestamp (check crowdsale contract)
/// @param _nameParam The name of the token.
/// @param _symbolParam The symbol of the token.
/// @param _tokenBaseCurrency The base currency.
/// @param _cap The max amount of tokens that can be minted.
/// @param _goal The goal of tokens that should be sold.
/// @param _startTime Time when crowdsale should start.
/// @param _endTime Time when crowdsale should end.
function setMetaData(
string calldata _nameParam,
string calldata _symbolParam,
address _tokenBaseCurrency,
uint256 _cap,
uint256 _goal,
uint256 _startTime,
uint256 _endTime)
external
canSetMetadata
{
require(_cap >= _goal, "cap higher goal");
_name = _nameParam;
_symbol = _symbolParam;
baseCurrency = _tokenBaseCurrency;
supply.cap = _cap;
supply.goal = _goal;
supply.startTime = _startTime;
supply.endTime = _endTime;
emit MetaDataChanged(msg.sender, _nameParam, _symbolParam, _tokenBaseCurrency, _cap, _goal);
}
/// @notice Set mint control role. Usually this is CONDA's controller.
/// @param _mintControl Contract address or wallet that should be allowed to mint.
function setMintControl(address _mintControl) public canSetMetadata { //ERROR: what on UPGRADE
roles.setMintControl(_mintControl);
}
/// @notice Set roles.
/// @param _pauseControl address that is allowed to pause.
/// @param _tokenRescueControl address that is allowed rescue tokens.
function setRoles(address _pauseControl, address _tokenRescueControl) public
canSetMetadata
{
roles.setRoles(_pauseControl, _tokenRescueControl);
}
function setTokenAlive() public
onlyOwnerOrOverruled
{
availability.setTokenAlive();
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public canTransfer returns (bool success) {
supply.doTransfer(availability, msg.sender, _to, _amount);
return true;
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition (requires allowance/approval)
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
return transferFromInternal(_from, _to, _amount);
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition (requires allowance/approval)
/// @dev modifiers in this internal method because also used by features.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFromInternal(address _from, address _to, uint256 _amount) internal canTransfer returns (bool success) {
return supply.transferFrom(availability, _from, _to, _amount);
}
/// @notice balance of `_owner` for this token
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` now (at the current index)
function balanceOf(address _owner) public view returns (uint256 balance) {
return supply.balanceOfNow(_owner);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` of his tokens
/// @dev This is a modified version of the ERC20 approve function to be a bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
return supply.approve(_spender, _amount);
}
/// @notice This method can check how much is approved by `_owner` for `_spender`
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed to spend
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return supply.allowed[_owner][_spender];
}
/// @notice This function makes it easy to get the total number of tokens
/// @return The total number of tokens now (at current index)
function totalSupply() public view returns (uint256) {
return supply.totalSupplyNow();
}
/// @notice Increase the amount of tokens that an owner allowed to a spender.
/// @dev 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) {
return supply.increaseApproval(_spender, _addedValue);
}
/// @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) {
return supply.decreaseApproval(_spender, _subtractedValue);
}
////////////////
// Miniting
////////////////
/// @dev Can rescue tokens accidentally assigned to this contract
/// @param _to The beneficiary who receives increased balance.
/// @param _amount The amount of balance increase.
function mint(address _to, uint256 _amount) public canMint returns (bool) {
return supply.mint(_to, _amount);
}
/// @notice Function to stop minting new tokens
/// @return True if the operation was successful.
function finishMinting() public onlyOwnerOrOverruled returns (bool) {
return availability.finishMinting();
}
////////////////
// Rescue Tokens
////////////////
/// @dev Can rescue tokens accidentally assigned to this contract
/// @param _foreignTokenAddress The address from which the balance will be retrieved
/// @param _to beneficiary
function rescueToken(address _foreignTokenAddress, address _to)
public
onlyTokenRescueControl
{
availability.rescueToken(_foreignTokenAddress, _to);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @notice Someone's token balance of this token
/// @dev Queries the balance of `_owner` at `_specificTransfersAndMintsIndex`
/// @param _owner The address from which the balance will be retrieved
/// @param _specificTransfersAndMintsIndex The balance at index
/// @return The balance at `_specificTransfersAndMintsIndex`
function balanceOfAt(address _owner, uint256 _specificTransfersAndMintsIndex) public view returns (uint256) {
return supply.balanceOfAt(_owner, _specificTransfersAndMintsIndex);
}
/// @notice Total amount of tokens at `_specificTransfersAndMintsIndex`.
/// @param _specificTransfersAndMintsIndex The totalSupply at index
/// @return The total amount of tokens at `_specificTransfersAndMintsIndex`
function totalSupplyAt(uint256 _specificTransfersAndMintsIndex) public view returns(uint256) {
return supply.totalSupplyAt(_specificTransfersAndMintsIndex);
}
////////////////
// Enable tokens transfers
////////////////
/// @dev this function is not public and can be overwritten
function enableTransferInternal(bool _transfersEnabled) internal {
availability.pauseTransfer(_transfersEnabled);
}
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed
function enableTransfers(bool _transfersEnabled) public
onlyOwnerOrOverruled
{
enableTransferInternal(_transfersEnabled);
}
////////////////
// Pausing token for unforeseen reasons
////////////////
/// @dev `pauseTransfer` is an alias for `enableTransfers` using the pauseControl modifier
/// @param _transfersEnabled False if transfers are allowed
function pauseTransfer(bool _transfersEnabled) public
onlyPauseControl
{
enableTransferInternal(_transfersEnabled);
}
/// @dev `pauseCapitalIncreaseOrDecrease` can pause mint
/// @param _mintingEnabled False if minting is allowed
function pauseCapitalIncreaseOrDecrease(bool _mintingEnabled) public
onlyPauseControl
{
availability.pauseCapitalIncreaseOrDecrease(_mintingEnabled);
}
/// @dev capitalControl (if exists) can reopen the crowdsale.
/// this function is not public and can be overwritten
function reopenCrowdsaleInternal() internal returns (bool) {
return availability.reopenCrowdsale();
}
/// @dev capitalControl (if exists) can enforce a transferFrom e.g. in case of lost wallet.
/// this function is not public and can be overwritten
function enforcedTransferFromInternal(address _from, address _to, uint256 _value, bool _fullAmountRequired) internal returns (bool) {
return supply.enforcedTransferFrom(availability, _from, _to, _value, _fullAmountRequired);
}
}
// File: contracts/assettoken/interfaces/ICRWDController.sol
interface ICRWDController {
function transferParticipantsVerification(address _underlyingCurrency, address _from, address _to, uint256 _amount) external returns (bool); //from AssetToken
}
// File: contracts/assettoken/interfaces/IGlobalIndex.sol
interface IGlobalIndex {
function getControllerAddress() external view returns (address);
function setControllerAddress(address _newControllerAddress) external;
}
// File: contracts/assettoken/abstract/ICRWDAssetToken.sol
contract ICRWDAssetToken is IBasicAssetTokenFull {
function setGlobalIndexAddress(address _globalIndexAddress) public;
}
// File: contracts/assettoken/CRWDAssetToken.sol
/*
Copyright 2018, CONDA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** @title CRWD AssetToken. This contract inherits basic functionality and extends calls to controller. */
contract CRWDAssetToken is BasicAssetToken, ICRWDAssetToken {
using SafeMath for uint256;
IGlobalIndex public globalIndex;
function getControllerAddress() public view returns (address) {
return globalIndex.getControllerAddress();
}
/** @dev ERC20 transfer function overlay to transfer tokens and call controller.
* @param _to The recipient address.
* @param _amount The amount.
* @return A boolean that indicates if the operation was successful.
*/
function transfer(address _to, uint256 _amount) public returns (bool success) {
ICRWDController(getControllerAddress()).transferParticipantsVerification(baseCurrency, msg.sender, _to, _amount);
return super.transfer(_to, _amount);
}
/** @dev ERC20 transferFrom function overlay to transfer tokens and call controller.
* @param _from The sender address (requires approval).
* @param _to The recipient address.
* @param _amount The amount.
* @return A boolean that indicates if the operation was successful.
*/
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
ICRWDController(getControllerAddress()).transferParticipantsVerification(baseCurrency, _from, _to, _amount);
return super.transferFrom(_from, _to, _amount);
}
/** @dev Mint function overlay to mint/create 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) public canMint returns (bool) {
return super.mint(_to,_amount);
}
/** @dev Set address of GlobalIndex.
* @param _globalIndexAddress Address to be used for current destination e.g. controller lookup.
*/
function setGlobalIndexAddress(address _globalIndexAddress) public onlyOwner {
globalIndex = IGlobalIndex(_globalIndexAddress);
}
}
// File: contracts/assettoken/feature/FeatureCapitalControl.sol
/*
Copyright 2018, CONDA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** @title FeatureCapitalControl. */
contract FeatureCapitalControl is ICRWDAssetToken {
////////////////
// Variables
////////////////
//if set can mint after finished. E.g. a notary.
address public capitalControl;
////////////////
// Constructor
////////////////
constructor(address _capitalControl) public {
capitalControl = _capitalControl;
enableTransferInternal(false); //disable transfer as default
}
////////////////
// Modifiers
////////////////
//override: skip certain modifier checks as capitalControl
function _canDoAnytime() internal view returns (bool) {
return msg.sender == capitalControl;
}
modifier onlyCapitalControl() {
require(msg.sender == capitalControl, "permission");
_;
}
////////////////
// Functions
////////////////
/// @notice set capitalControl
/// @dev this looks unprotected but has a checkCanSetMetadata check.
/// depending on inheritance this can be done
/// before alive and any time by capitalControl
function setCapitalControl(address _capitalControl) public {
require(checkCanSetMetadata(), "forbidden");
capitalControl = _capitalControl;
}
/// @notice as capital control I can pass my ownership to a new address (e.g. private key leaked).
/// @param _capitalControl new capitalControl address
function updateCapitalControl(address _capitalControl) public onlyCapitalControl {
capitalControl = _capitalControl;
}
////////////////
// Reopen crowdsale (by capitalControl e.g. notary)
////////////////
/// @notice capitalControl can reopen the crowdsale.
function reopenCrowdsale() public onlyCapitalControl returns (bool) {
return reopenCrowdsaleInternal();
}
}
// File: contracts/assettoken/feature/FeatureCapitalControlWithForcedTransferFrom.sol
/*
Copyright 2018, CONDA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** @title FeatureCapitalControlWithForcedTransferFrom. */
contract FeatureCapitalControlWithForcedTransferFrom is FeatureCapitalControl {
///////////////////
// Constructor
///////////////////
constructor(address _capitalControl) FeatureCapitalControl(_capitalControl) public { }
///////////////////
// Events
///////////////////
event SelfApprovedTransfer(address indexed initiator, address indexed from, address indexed to, uint256 value);
///////////////////
// Overrides
///////////////////
//override: transferFrom that has special self-approve behaviour when executed as capitalControl
function transferFrom(address _from, address _to, uint256 _value) public returns (bool)
{
if (msg.sender == capitalControl) {
return enforcedTransferFromInternal(_from, _to, _value, true);
} else {
return transferFromInternal(_from, _to, _value);
}
}
}
// File: contracts/assettoken/STOs/AssetTokenT001.sol
/** @title AssetTokenT001 Token. A CRWDAssetToken with CapitalControl and LostWallet feature */
contract AssetTokenT001 is CRWDAssetToken, FeatureCapitalControlWithForcedTransferFrom
{
constructor(address _capitalControl) FeatureCapitalControlWithForcedTransferFrom(_capitalControl) public {}
} | This is the actual transfer function in the token contract, it can only be called by other functions in this contract. Check for availability must be done before. _from The address holding the tokens being transferred _to The address of the recipient _amount The amount of tokens to be transferred return True if the transfer was successful Do not allow transfer to 0x0 or the token contract itself If the amount being transfered is more than the balance of the account the transfer throws First update the balance array with the new value for the address sending the tokens Then update the balance array with the new value for the address receiving the tokensinfo: don't move this line inside updateValueAtNow (because transfer is 2 actions) An event to make the transfer easy to find on the blockchain | function doTransfer(Supply storage _self, Availability storage /*_availability*/, address _from, address _to, uint256 _amount) public {
require(_to != address(0), "addr0");
require(_to != address(this), "target self");
uint256 previousBalanceFrom = balanceOfNow(_self, _from);
require(previousBalanceFrom >= _amount, "not enough");
updateValueAtNow(_self, _self.balances[_from], previousBalanceFrom.sub(_amount));
uint256 previousBalanceTo = balanceOfNow(_self, _to);
updateValueAtNow(_self, _self.balances[_to], previousBalanceTo.add(_amount));
increaseTokenActionIndex(_self);
emit Transfer(_from, _to, _amount);
}
| 6,461,827 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.